How to access data from a TXT file in the C programming language?
In C language, file operation functions can be used to read and write data in a TXT file.
To read data from a TXT file, you can follow these steps:
- open a file
- Open a file and return a file pointer using the provided filename and mode.
- the name of the file
- fashion
- “r” means the letter “r” in the English alphabet.
- Reads formatted input from a stream
- The function fscanf reads formatted input from a file stream.
- flow
- presentation style
- I don’t understand the assignment.
- to close (as in a file or document)
- Close the file pointed to by the stream.
- – a flowing body of water
Here is a simple example code demonstrating how to read data from a TXT file and output it to the console.
#include <stdio.h>
int main() {
FILE *file;
int num;
file = fopen("data.txt", "r"); // 打开名为"data.txt"的文件
if (file == NULL) {
printf("无法打开文件!\n");
return 1;
}
while (fscanf(file, "%d", &num) != EOF) { // 读取整数数据
printf("%d ", num);
}
fclose(file); // 关闭文件
return 0;
}
To write data into a TXT file, you can follow these steps:
- open a file
- Open a file with the specified filename and mode and return a FILE pointer.
- file name
- fashion
- “double-u”
- write/send a formatted output
- This function writes formatted output to a stream.
- stream – a continuous flow of water in a river or other watercourse
- layout
- I need a moment to gather my thoughts before responding.
- close a file
- Close the file associated with the stream.
- – flow
Here is a simple code example demonstrating how to write data to a TXT file.
#include <stdio.h>
int main() {
FILE *file;
int num;
file = fopen("data.txt", "w"); // 打开名为"data.txt"的文件
if (file == NULL) {
printf("无法打开文件!\n");
return 1;
}
printf("请输入一个整数:");
scanf("%d", &num);
fprintf(file, "%d", num); // 将整数写入文件
fclose(file); // 关闭文件
return 0;
}
Note: The above sample code assumes that the TXT file only contains integer data. If you need to read or write other types of data, you can make the necessary modifications accordingly.