how to read and write to fiel n c
#include <stdio.h>
int main() {
FILE *filePointer;
char data[100];
// Writing to a file
filePointer = fopen("file.txt", "w");
if (filePointer == NULL) {
printf("File could not be opened.");
return 1;
}
printf("Enter some text to write into the file: ");
fgets(data, sizeof(data), stdin);
fprintf(filePointer, "%s", data);
fclose(filePointer);
// Reading from a file
filePointer = fopen("file.txt", "r");
if (filePointer == NULL) {
printf("File could not be opened.");
return 1;
}
printf("Content from the file:\n");
while (fgets(data, sizeof(data), filePointer) != NULL) {
printf("%s", data);
}
fclose(filePointer);
return 0;
}
Explanation:
#include <stdio.h>
: Includes the standard I/O library in C, necessary for file handling.FILE *filePointer;
: Declares a pointer to a FILE type which will be used to access the file.char data[100];
: Declares an arraydata
capable of storing 100 characters, used to hold user input and content read from the file.filePointer = fopen("file.txt", "w");
: Opens a file namedfile.txt
in write mode. If the file does not exist, it will be created. If it exists, its content will be truncated.if (filePointer == NULL) { printf("File could not be opened."); return 1; }
: Checks if the file opening operation was successful. If the file couldn't be opened, an error message is printed, and the program exits with an error code (1
).printf("Enter some text to write into the file: "); fgets(data, sizeof(data), stdin);
: Prompts the user to enter text to write into the file.fgets()
reads the input from the standard input (stdin
) and stores it in thedata
array.fprintf(filePointer, "%s", data);
: Writes the content of thedata
array into the file usingfprintf()
.fclose(filePointer);
: Closes the file after writing.filePointer = fopen("file.txt", "r");
: Opens the same file in read mode to read its content.if (filePointer == NULL) { printf("File could not be opened."); return 1; }
: Checks if the file opening operation was successful for reading. If not, an error message is printed, and the program exits with an error code (1
).while (fgets(data, sizeof(data), filePointer) != NULL) { printf("%s", data); }
: Reads the content of the file line by line usingfgets()
and prints it to the console until the end of the file (NULL
) is reached.fclose(filePointer);
: Closes the file after reading.