Embedded World

[C] C의 파일시스템, fopen_s() 본문

소프트웨어/C

[C] C의 파일시스템, fopen_s()

jh-rrr 2025. 7. 24. 20:20

C에서 파일의 데이터를 읽거나 쓸 경우 파일 입출력 함수인 fopen_s()를 사용하게 된다.

 

fopen_s의 구문은 다음과 같다.

errno_t fopen_s(
   FILE** pFile,
   const char *filename,
   const char *mode
);

매개변수

pFile : 열린 파일에 대한 포인터를 받는 파일 포인터에 대한 포인터이다.

filename : 열어야 할 파일의 이름이다.

mode : 허용되는 엑세스 형식이다.

반환 값

성공 시 0이고, 실패 시 오류 코드를 반환한다.

 

예시 코드

// crt_fopen_s.c
// This program opens two files. It uses
// fclose to close the first file and
// _fcloseall to close all remaining files.

#include <stdio.h>

FILE *stream, *stream2;

int main( void )
{
   errno_t err;

   // Open for read (will fail if file "crt_fopen_s.c" doesn't exist)
   err  = fopen_s( &stream, "crt_fopen_s.c", "r" );
   if( err == 0 )
   {
      printf( "The file 'crt_fopen_s.c' was opened\n" );
   }
   else
   {
      printf( "The file 'crt_fopen_s.c' was not opened\n" );
   }

   // Open for write
   err = fopen_s( &stream2, "data2", "w+, ccs=UTF-8" );
   if( err == 0 )
   {
      printf( "The file 'data2' was opened\n" );
   }
   else
   {
      printf( "The file 'data2' was not opened\n" );
   }

   // Close stream if it isn't NULL
   if( stream )
   {
      err = fclose( stream );
      if ( err == 0 )
      {
         printf( "The file 'crt_fopen_s.c' was closed\n" );
      }
      else
      {
         printf( "The file 'crt_fopen_s.c' was not closed\n" );
      }
   }

   // All other files are closed:
   int numclosed = _fcloseall( );
   printf( "Number of files closed by _fcloseall: %u\n", numclosed );
}

출력

The file 'crt_fopen_s.c' was opened
The file 'data2' was opened
Number of files closed by _fcloseall: 1

 

 

 

refernece https://learn.microsoft.com/ko-kr/cpp/c-runtime-library/reference/fopen-s-wfopen-s?view=msvc-170