Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

fopen does not create a file

+8 votes
asked May 3 by John Chung (330 points)
Hi.

I have a very simple program to create a file. (I am trying to learn). Even though the code returns(0) it never creates a file. I can create the same file in the same directory using powershell. Any suggestions would be appreciated.

Here is the code:

#include <stdio.h>

#include <stdlib.h>

 int main ()

 {

int num;

  

FILE * fptr;

  

fptr = fopen ("C:\\test\Myprogram.txt", "w");

  

if (fptr == NULL)

{

  

printf ("Error!");

  

exit (1);

}

  

printf ("Enter num: ");

  

scanf ("%d", &num);

  

fprintf (fptr, "%d", num);

  

fclose (fptr);

  

return 0;

}

1 Answer

+1 vote
answered May 3 by Peter Minarik (88,520 points)

The code successfully creates a file for me in OnlineGDB.

However, please remember that your local Windows and the Linux (of OnlineGDB) operating systems and the C language on them may work slightly differently.

Please note, that you're missing a '\' from your path. Your path should correctly be: "C:\\test\\Myprogram.txt".

If that still does not allow your code to work, make sure that the C:\test directory exists as fopen() does not create the directory hierarchy for you.

Good luck!

commented May 5 by John Chung (330 points)
thank you. I will fix that error and try again.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...