C Programming/File Manipulation
Jump to navigation
Jump to search
When accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. For Example:
FILE *fp;
To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.
FILE *fopen(const char *filename, const char *mode);
Here filename is string literal which you will use to name your file and mode can have one of the following values
w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)
File Write
//main.c
#include <stdio.h>
int main(void)
{
FILE *fp;
fp = fopen("./test.txt", "w");
fprintf(fp, "Hello text archive\n");
//fclose(fp;);
fclose(fp);
return 0;
}
File Read
//main.c
#include <stdio.h>
int main(void)
{
FILE *fp;
char buffer[20];
fp = fopen("./test.txt", "r");
fscanf(fp, "%s", buffer);
//printf("Read Buffer: %s\n", %buffer);
printf("Read Buffer: %s\n", buffer);
//fclose(fp;);
fclose(fp);
return 0;
}
Binary IO
//for read binary data from file
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
//for write binary data into file
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);