C言語でファイルからデータを読み込む方法

ファイルからデータを読み取るには、C言語で以下のようにします。

  1. open()
FILE *file = fopen("filename.txt", "r");
  1. ファイルを開く
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
  1. fscanf()
  2. fgets()
  3. fscanf()
  4. fgets()
int data;
// 使用fscanf()函数读取整数
fscanf(file, "%d", &data);
char line[100];
// 使用fgets()函数读取一行数据
fgets(line, sizeof(line), file);
  1. fclose()
fclose(file);

数値と文字列をファイルから読み込む完全なサンプルコードを以下に示します。

#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
int number;
fscanf(file, "%d", &number);
printf("读取的整数为:%d\n", number);
char line[100];
fgets(line, sizeof(line), file);
printf("读取的字符串为:%s\n", line);
fclose(file);
return 0;
}

実行時にdata.txtファイルが存在し適切なデータが含まれていることを確認してください。

コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds