c-language file operations
In c-language file operation,files include text files and binaries.Both of them exist as streams in system.
Three important streams about terminal.
When a file is written, the written data is stored in the cache.
1.stdin (standard input streams)
2.stdout (standard output streams)
3.stderr (standard error streams)
Open files.
function prototype :
FILE *fopen(const char *path, const char *mode);
parameter:
The string “path” contains path and filename of the file to open.The string “mode” represents the type of stream to open.
Some tips of parameter “mode” :
- With ‘+’ for read/write, read/write is allowed.
- Contains ‘b’ for open binary file, otherwise for text file.
- ‘r’, read only open;If and only if it contains ‘r’, the file must exist, otherwise you can create a new file.
- ‘w’, write, if there is a file, then delete and then new, equivalent to write from scratch.
- ‘a’, append, write at the end.
eg:
*FILE fp=fopen(“file.txt”,“r”);
Close files.
function prototype :
int fclose(FILE *stream);
eg:
fclos(fp);
After manipulating the file,remeber to close it.
the read and write operations of files.
“fgets” and “fputs”
fgets
Function “fgets” is used to read data from files.
function prototype :
char *fgets(char *s, int size, FILE *stream);
fputs
Function “fputs” is used to write data to files.
function prototype :
int fputs(const char *s, FILE *stream);
“fscanf” and “fprintf”
fscanf
It is used to formatted read.
function prototype :
int fscanf(FILE *stream, const char *format, …);
fprintf
It is used to formatted write.
function prototype :
int fprintf(FILE *stream, const char *format, …);
“fread” and “fwrite”
fread
It is used to read data from a binary file.
function prototype :
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
fwrite
The data to be written to a file is written to the file in binary form.
function prototype :
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);