Creating a file using fopen()

Popeye picture Popeye · Aug 4, 2015 · Viewed 11.4k times · Source

I am just creating a basic file handling program. the code is this:

#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
    printf("Error",);

}

fclose(p);
}

This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success. I am using Windows 7 and compiler is Dev C++ version 5

Answer

ryyker picture ryyker · Aug 4, 2015

Change the open(const char *filename, const char *mode) mode argument from:

p=fopen("D:\\TENLINES.TXT","r");//this will not _create_ a file
if(p==0)                //  ^

To this:

p=fopen("D:\\TENLINES.TXT","w");//this will create a file for writing.
if(p==NULL)             //  ^   //If the file already exists, it will write over
                                //existing data.

If you want to add content to an existing file, you can use "a+" for the open mode.

Reference for fopen (for more open modes, and additional information about the fopen family of functions)