C言語 txtファイル データ修正の基本と実践
C言語のファイル操作関数を使って、txtファイルのデータを変更することができます。以下は、txtファイル内のデータを変更する方法を示す簡単なサンプルコードです。
#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;
}
このサンプルコードでは、最初に「example.txt」という名前のファイルを開いて、ファイルからデータを読み取り出力します。次に、ファイルポインタをファイルの先頭に再配置し、新しいデータ「New Data to be written」をファイルに書き込みます。最後にファイルを閉じて変更された情報を出力します。
こちらは単なるサンプルコードであり、実際のアプリケーションではより多くのエラーハンドリングやデータ処理ロジックが必要になる場合があります。