Creating new text file in c
In C, you can create a new text file using the fopen()
function, which returns a file pointer to the file. Here's an example:
#include <stdio.h>
int main() {
FILE *fp;
char filename[] = "newfile.txt"; // name of the file to create
// open the file in write mode (create a new file if it doesn't exist)
fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
// write some text to the file
fprintf(fp, "This is a new file created in C.\n");
fprintf(fp, "Hello, world!\n");
// close the file
fclose(fp);
return 0;
}
In this example, we:
- Define a character array
filename
to store the name of the file we want to create. - Use
fopen()
to open the file in write mode ("w"
). If the file doesn't exist,fopen()
will create it. If the file already exists, its contents will be truncated. - Check if the file was opened successfully by checking if
fp
isNULL
. If it is, print an error message and return an error code. - Use
fprintf()
to write some text to the file. - Close the file using
fclose()
.
Note that if you want to append to an existing file instead of creating a new one, you can use the "a"
mode instead of "w"
.
Also, don't forget to include the stdio.h
header file at the top of your program to use the fopen()
, fprintf()
, and fclose()
functions.