文件输入输出 c语言

c语言使用fopen(const char* fileName, const char* mode);返回对应文件的指针FILE*

文件不存在 是否可读 如何写入
“r” 出错 不可泄
“w” 创建 清空后写入
“a” 创建 追加写入
“r+” 出错 覆盖式写入
“w+” 创建 清空后写入
“a+” 创建 追加写入
1
2
3
4
5
FILE* file = fopen("test", "a+");
if (file == NULL) {
cout << "open file failed" << endl;
return 1;
}

打开文件后可以使用fscanf来读取文件的数据 fscanf(file, "%d %d", &a, &b);

或用fprintf来向文件写入数据 fprintf(file, "%d\n", a + b);

第一个参数需要传入文件的指针

char ch = fgetc(file); fputc(ch, file);获取和输出单个字符

fgets(str, 100, file); fputs(str, file); 来读入和输出整行的字符串

使用完文件后 调用fclose(file);进行关闭

文件输入输出 c++

在头文件 <fstream>中 通过fstream类型来定义文件流

fstream fio("text.txt", ios::in | ios::out | ios::app);

其中in代表读入 out代表清空后写入 app是append的缩写,代表追加,多个模式相加使用|

  • ifstream openFileIn("filename", ios::in);:打开文件用于读取
  • ofstream openFileOut("filename", ios::out);:打开文件用于写入
  • fstream openFileInOut("filename", ios::in | ios::out);:打开文件用于读写
1
2
3
4
5
6
7
fstream fio("text.txt", ios::in | ios::out | ios::app);
fio >> a >> b;
fio << a << b;
ifstream fin("test.txt", ios::in);
ofstream fout("test.txt", ios::app);
fin >> a >> b;
fout << a << b;

fio.close(), fin.close(), fout.close();进行关闭

文件读写

  • char ch; fileIn.get(ch);:从文件中读取一个字符

  • string str; getline(fileIn, str);:从文件中读取一行字符串

  • char ch = 'A'; fileOut.put(ch);:向文件写入一个字符

  • fout.write(const char* str, streamsize n);

  • string str = "Hello"; fileOut << str;:向文件写入一个字符串

移动文件指针

  • fileIn.seekg(0, ios::beg);:将输入文件指针移动到文件开头
  • fileOut.seekp(0, ios::beg);:将输出文件指针移动到文件开头

文件状态检查

  • if (fileIn.eof()) { ... }:检查是否到达文件末尾

  • if (!fileIn) { ... }:检查文件是否打开失败或发生错误

在头文件<sstream>

1
2
3
4
int a, b;
string str = "1 2";
stringstream ss(str);
ss >> a >> b;