Alright! Let's talk about file pointers in C. Today I learned the following ๐
OPERATIONS OF FILE POINTERS IN C
- "r" = read
- "w"= write
- "a" = append
Write vs Append
For write, if the file already exists it will overwrite the whole file with the new data. Meanwhile append, will write the new data right after the end of the file and add to it new data. So append, will not lose any data that was there before.
FILE OPEN: fopen()
- opens a file and returns a file pointer to it
- Always check the return value to make sure you don't get back NULL
How to use:
For this example we will use the variable ptr...but you can choose whatever.
FILE* ptr = fopen(filename, operation);
How do we check if the function can open the file? ๐
FILE* ptr = fopen(argv[1], "r");
if (file == NULL)
{
printf("Can not open file\n");
return 1;
}
FILE CLOSE: fclose()
- closes the file pointed to by the given file pointer.
How to use:
fclose(file pointer);
in our case:
fclose(ptr);
FILE GET: fgetc()
- Reads and returns the next character from the file pointed to
- NOTE: The file must have been opened with operation READ "r"
How to use:
char ch = fgetc(file pointer);
in our case:
char ch = fgetc(ptr);
We can print out all the character of the file like this:
char ch
while((ch = fgetc(ptr)) != EOF)
printf("%c", ch);
EOF = End of file. It's a special value defined in the library stdio.h
FILE PUT: fputc()
- Writes or appends the specific character to the pointed file.
- NOTE: The file must have been opened with operation WRITE "w" or APPEND "a"
How to use:
fputc(character, file pointer);
in our case:
fputc('A', ptr);
We can now read characters from one file and write in another for example:
char ch
while((ch = fgetc(ptr)) != EOF)
fputc(ch, ptr1);
FILE READ: fread()
READS FROM THE FILE TO THE BUFFER.
- Reads qty units of size size from the file pointed to and stores them in memory in a buffer (usually an array) pointed to by buffer -NOTE: The operation of the file pointer passed in as a parameter must be READ "r" or you will suffer an error.
How to use:
fread(buffer, size, qty, file pointer);
an example case:
int arr[10]
fread(arr, sizeoff(int), 10, ptr);
FILE WRITE: fwrite()
BASICALLY THE OPPOSITE OF fread(), READS FROM THE BUFFER TO THE FILE.
- Write qty units of size size to the file pointed to by reading them from a buffer (usually an array) pointed to by buffer -NOTE: the operation of the file pointer passed in as a parameter must be "w"or "a"or will suffer an error.
How to use:
fwrite(buffer, size, qty, file pointer);
an example case:
int arr[10]
fread(arr, sizeoff(int), 10, ptr);