Edit TXT Files in C: Full Guide
To modify the data in a txt file, you can use the file operation functions in C language. Below is a simple example code demonstrating how to modify data in a txt file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *file;
char filename[] = "example.txt";
char data[1000];
char newData[] = "New Data to be written";
// 打开文件以进行读写操作
file = fopen(filename, "r+");
if (file == NULL) {
printf("Error opening file.");
return 1;
}
// 读取文件中的数据
fgets(data, sizeof(data), file);
printf("Original data: %s\n", data);
// 将文件指针重新定位到文件开头
fseek(file, 0, SEEK_SET);
// 写入新的数据到文件中
fputs(newData, file);
// 关闭文件
fclose(file);
printf("Data in file has been modified.\n");
return 0;
}
In this sample code, we first open a file named “example.txt”, then read and output the data in the file. Next, we reposition the file pointer to the beginning of the file and write new data “New Data to be written” into the file. Finally, we close the file and output the modified information.
Please note that this is just a simple example code and in actual applications, more error handling and data processing logic may be needed.