Creating a file using the fopen () function
I am just building a basic file handling program. this is the code:
#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
printf("Error",);
}
fclose(p);
}
This gives an error, I cannot create files that tried to reinstall the compiler and use different locations and filenames, but did not succeed. I am using Windows 7 and the compiler is Dev C ++ version 5
Change the opening mode:
p=fopen("D:\\TENLINES.TXT","r");//this will not _create_ a file
if(p==0)
For 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 open mode.
Link for fopen (for more open modes and more information on the fopen family of functions)
According to the tutorial , it fopen
returns NULL on error. Therefore you have to check if it matches p
NULL
.
Also, printf("Error",);
omit the comma after the line.
Yes, you must open the file in write mode. Which creates the file. Read mode is only for reading content, or you can use "r +" for reading and writing.