Search code examples
cfileerror-handlingfopen

Open a file in c as securely as possible


I would write a program as follows

int main ()
{
      FILE *fp = fopen("test.txt", "r")

      if (fp == NULL)
      {
           printf("Sorry, file doesn't exist.");
           return 0;     
      }

   return 0;
} 

Is there any other check that I would need to make sure before or after opening a file?

What if the opening of a file can damage the system(virus)? is there any check for that?

What if the file is not a .txt file, user just renamed mp3 file to a txt file?


Solution

  • No other check needed.

    I always also make it a practice of calling fclose, however, when done with the FILE*.