How to call a file in the C language?
C language can call a file through the following steps:
- Open file
- Document
FILE *file = fopen("filename.txt", "r");
- read an input from a file in C
- write in a specific format
- input data
- print or display
int number;
fscanf(file, "%d", &number);
int number = 42;
fprintf(file, "%d", number);
- Close the file.
fclose(file);
It is important to note that before using a file, you should check if the file has been successfully opened and if any errors occurred while operating the file. You can use the feof function to check if the file has reached its end, or use the ferror function to check for errors. Example code is as follows:
if (file == NULL) {
printf("文件打开失败\n");
return -1;
}
if (ferror(file)) {
printf("文件操作错误\n");
return -1;
}
if (feof(file)) {
printf("文件已到达末尾\n");
}
The above are basic file operation steps, which can be adjusted and expanded according to specific needs.