0% found this document useful (0 votes)
4 views

file handling codes

The document contains three C programming examples: writing to a file, appending to a file, and reading from a file. Each example includes error handling for file operations and demonstrates basic file I/O functions such as fopen, fprintf, fgets, and fclose. The code snippets illustrate how to create, modify, and read text files in C.

Uploaded by

dedarkshadowyt66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

file handling codes

The document contains three C programming examples: writing to a file, appending to a file, and reading from a file. Each example includes error handling for file operations and demonstrates basic file I/O functions such as fopen, fprintf, fgets, and fclose. The code snippets illustrate how to create, modify, and read text files in C.

Uploaded by

dedarkshadowyt66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Writing to a File
#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *filePointer;

filePointer = fopen("sample.txt", "w");

if (filePointer == NULL) {

printf("Error opening file for writing!\n");

exit(1);

fprintf(filePointer, "Hello world.\n");

fclose(filePointer);

return 0;

}
2. Appending to a File
#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *filePointer;

filePointer = fopen("append.txt", "a");

if (filePointer == NULL) {

printf("Error opening file for appending!\n");

exit(1);

fprintf(filePointer, "Appending some words.\n");

fclose(filePointer);

return 0;

}
3. Reading from a File
#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *filePointer;

char data[100];

filePointer = fopen("sample.txt", "r");

if (filePointer == NULL) {

printf("Error opening file for reading! File does not exist.\n");

exit(1);

while (fgets(data, sizeof(data), filePointer) != NULL) {

printf("%s", data);

fclose(filePointer);

return 0;

You might also like