SImple C Program opening a file

user485498 picture user485498 · Feb 16, 2011 · Viewed 75.6k times · Source

I'm trying to make a program to open a file, called "write.txt".

#include <stdio.h>

main() {
    FILE *fp;
    fp = fopen("write.txt", "w");
    return 0;
 }

Should this work? Because it returns nothing.

Answer

paxdiablo picture paxdiablo · Feb 16, 2011

Other than an old variant of main, there's not really much wrong with that code. It should, barring errors, create the file.

However, since you're not checking the return value from fopen, you may get an error of some sort and not know about it.

I'd start with:

#include <stdio.h>
#include <errno.h>
int main (void) {
    FILE *fp;
    fp = fopen ("write.txt","w");
    if (fp == NULL) {
        printf ("File not created okay, errno = %d\n", errno);
        return 1;
    }
    //fprintf (fp, "Hello, there.\n"); // if you want something in the file.
    fclose (fp);
    printf ("File created okay\n");
    return 0;
}

If you're adamant that the file isn't being created but the above code says it is, then you may be a victim of the dreaded "IDE is working in a different directory from what you think" syndrome :-)

Some IDEs (such as Visual Studio) will actually run your code while they're in a directory like <solution-name>\bin or <solution-name>\debug. You can find out by putting:

system ("cd"); // for Windows
system ("pwd") // for UNIXy systems

in to your code to see where it's running. That's where a file will be created if you specify a relative path line "write.txt". Otherwise, you can specify an absolute path to ensure it tries to create it at a specific point in the file system.