Search
In C, files are accessed through file pointers of type FILE *. You open files with fopen() and close them with fclose().
FILE *
fopen()
fclose()
FILE *pFile = fopen("filename.txt", "r"); if (pFile == NULL) { printf("Failed to open file\n"); } else { // perform I/O operations fclose(pFile); }
int fgetc(FILE *stream)
unsigned char
EOF
int fputc(int c, FILE *stream)
int ch; while ((ch = fgetc(pFile)) != EOF) { fputc(ch, outFile); }
char *fgets(char *str, int size, FILE *stream)
size-1
int fputs(const char *str, FILE *stream)
char buffer[100]; while (fgets(buffer, sizeof(buffer), file)) { fputs(buffer, stdout); }
int fscanf(FILE *stream, const char *format, ...)
int fprintf(FILE *stream, const char *format, ...)
char text[50]; FILE *pFile = fopen("filename.txt", "r"); while (fscanf(pFile, "%s", text) == 1) { printf("%s\n", text); } fclose(pFile);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
nmemb
size
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
typedef struct { char name[50]; int age; } Person; //Write Person p1 = {"Alice", 25}; FILE *f = fopen("people.dat", "wb"); fwrite(&p1, sizeof(Person), 1, f); fclose(f); //Read Person p2; FILE *f = fopen("people.dat", "rb"); fread(&p2, sizeof(Person), 1, f); printf("%s is %d\n", p2.name, p2.age); fclose(f);
c_poem.txt
c_poem_censored.txt
C
*
Copy the following text to the c_poem.txt file:
In the realm of code, C stands tall, a robust language, embraced by all. With syntax concise, and power untold, it crafts systems, timeless and bold. Pointers dance in memory's maze, arrays align in structured arrays. Functions echo, a symphony of logic, in C's embrace, a coder's magic. From main to end, the journey unfolds, loops and branches, stories untold. Efficiency reigns in every line, in the heart of C, brilliance aligns. Header files whisper of libraries vast, A tapestry woven, from present to past. C, the maestro in the coding symphony, Crafting elegance in binary harmony. - ChatGPT
fgets()
stdout
printf(“%s\n”, …)
copy.txt
fputs()
contacts.txt
fscanf()
scanf(…)
fscanf(stdin, …)
fprintf()
Copy the following text to the contacts.txt file:
Miles 23 Leonardo 31 George 22 Frederique 40 Robin 4 Riccardo 35