In C, files are accessed through file pointers of type FILE *.
You open files with fopen() and close them with fclose().
FILE *pFile = fopen("filename.txt", "r"); if (pFile == NULL) { printf("Failed to open file\n"); } else { // perform I/O operations fclose(pFile); }
| “r” | Read an existing file. |
| “w” | Write: create new or erase existing file. |
| “a” | Append: add to end, create if missing. |
| “r+” | Read and write an existing file. |
| “w+” | Read and write, create new or erase existing. |
| “a+” | Read and append, create if missing. |
| “rb/wb/ab” | Same as above but binary mode. |
int fgetc(FILE *stream)
unsigned char converted to int, or EOF on end-of-file or error
int fputc(int c, FILE *stream)
EOF on error
int ch; while ((ch = fgetc(pFile)) != EOF) { fputc(ch, outFile); }
char *fgets(char *str, int size, FILE *stream)
size-1 characters or until newline, whichever comes first.
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 elements of size bytes each into memory
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
nmemb elements of size bytes each from memory to file
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 in read mode
c_poem_censored.txt in write mode
C with *
c_poem_censored.txt
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
c_poem_censored.txt in read mode
fgets()
stdout using printf(“%s\n”, …)
copy.txt, using fputs()
contacts.txt
fscanf() to read names and ages
scanf(…) or fscanf(stdin, …) and add new entries to the contacts.txt file using fprintf()
Copy the following text to the contacts.txt file:
Miles 23 Leonardo 31 George 22 Frederique 40 Robin 4 Riccardo 35