Examples of standard sentences for input and output of C language from files
We have a file named target.txt, the content is:
123
fopen() can be input from a file, as follows:
#include <stdio.h>
int main(){
FILE *fp = fopen("target.txt","r");
if(fp){
int num;
fscanf(fp, "%d", &num); //从文件输入数字
printf("%d\n", num);
fclose(fp);
}else{
printf("无法打开文件\n");
}
return 0 ;
}
123
The C library function FILE *fopen(const char *filename, const char *mode) can use the given mode mode to open the file pointed to by filename. ilename-This is a C string containing the name of the file to be opened. mode is the file access mode, which can be selected as follows:
mode | description |
---|---|
“r” | Open a file for reading, the file must exist |
“r+ '” | Open for reading and writing, starting from the beginning of the file |
" w’" | Open and write only, if the file does not exist, create a new one, if it exists, empty it |
" w+“ | Open for reading and writing, create a new file if it does not exist, and clear it if it exists |
“a '” | Open append. If it does not exist, create a new one, if it exists, start from the header file |
“a+ '” | Open a file for reading and appending. |
“’.x” | Only create a new file, if the file already exists, it cannot be opened |
Now we write to the file
#include <stdio.h>
int main(){
FILE *fp = fopen("12.txt","w+");
if(fp){
int num;
fscanf(fp, "%d", &num);
printf("%d\n", num);
fprintf(fp,"%s%s%d","hello","wrold",2020);
fclose(fp);
}else{
printf("无法打开文件\n");
}
return 0 ;
}
Let us compile and run the above program, the original file will be cleared and written into target.txt:
Hello wrold2020
If we don’t want to overwrite the original file content, we can append
int main(){
FILE *fp = fopen("12.txt","a");
if(fp){
int num;
// fscanf(fp, "%d", &num);
// printf("%d\n", num);
fprintf(fp,"%s%s%d","你好","wrold",2020);
fclose(fp);
}else{
printf("无法打开文件\n");
}
return 0 ;
}
After permission, the content of target.txt is as follows:
Hello wrold2020 hello wrold2020
So we can read and write the file.