C++/C文件读取
1、C++文件操作
- ofstream:寫操作
- ifstream: 讀操作
- fstream : 讀寫操作
| 打開方式 | 解釋 |
|---|---|
| ios::in | 為讀文件而打開文件 |
| ios::out | 為寫文件而打開文件 |
| ios::ate | 初始位置:文件尾 |
| ios::app | 追加方式寫文件 |
| ios::trunc | 如果文件存在先刪除,再創建 |
| ios::binary | 二進制方式 |
1.1、寫文件
-
包含頭文件
#include <fstream>
-
創建流對象
ofstream ofs;
-
打開文件
ofs.open(“文件路徑”,打開方式);
-
寫數據
ofs << “寫入的數據”;
-
關閉文件
ofs.close();
#include<fstream>
#include<iostream>
using namespace std;
int main()
{ofstream ofs;ofs.open("D:\\學習資料整理\\C++資料\\test.txt", ios::out|ios::app);ofs << "C++" << endl;ofs.close();
}
1.2、讀文件
-
包含頭文件
#include <fstream>
-
創建流對象
ifstream ifs;
-
打開文件并判斷文件是否打開成功
ifs.open(“文件路徑”,打開方式);
-
讀數據
讀取數據
-
關閉文件
ifs.close();
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{ifstream ifs;ifs.open("D:\\學習資料整理\\C++資料\\test.txt", ios::in);if (!ifs.is_open()){cout << "文件打開失敗" << endl;}// 讀取一行數據string res;while (getline(ifs, res)){cout << res << endl;}
}
2、C文件操作
| 文件使用方式 | 含義 | 如果指定的文件不存在 |
|---|---|---|
| r(只讀) | 輸入數據,打開一個已存在文本文件 | 出錯 |
| w(只寫) | 輸出數據,打開一個文本文件 | 建立一個新文件 |
| a(追加) | 向文本文件尾添加數據 | 出錯 |
| rb(只讀) | 輸入數據,打開一個2進制文件 | 出錯 |
| wb(只寫) | 輸出數據,打開一個2進制文件 | 建立新文件 |
| r+(讀寫) | 讀寫,文本文件 | 出錯 |
| w+(讀寫) | 讀寫,文本文件 | 建立新文件 |
| a+(讀寫) | 讀寫,文本文件 | 出錯 |
| rb+(讀寫) | 讀寫,二進制文件 | 出錯 |
| wb+(讀寫) | 讀寫,二進制文件 | 建立新文件 |
| ab+(讀寫) | 讀寫二進制文件 | 出錯 |
C++不支持fopen等函數,改用fopen_s等,如果想改變的話:
右鍵工程名–>屬性–>C/C++–>預處理器–>預處理器定義,編輯右邊輸入框加入:
_CRT_SECURE_NO_WARNINGS
2.1、寫文件
2.1.1、fputs
#include<iostream>
#include<string>
using namespace std;
int main()
{FILE* file;string str = "python\n";// 在C++中,fopen已經不能使用// a+表示追加讀寫方式// fopen_s函數如果打開文件成功的話,返回0if (fopen_s(&file, "D:\\學習資料整理\\C++資料\\test.txt", "a+") != 0){cout << "文件打開失敗" << endl;}// 將string轉為char*fputs(str.c_str(), file);fclose(file);
}
2.1.2、fprintf_s
| 名稱 | 引用方式 |
|---|---|
| fprintf_s | fprintf_s(文件指針,格式字符串) |
#include<iostream>
#include<string>
using namespace std;
int main()
{FILE* file;if (fopen_s(&file, "D:\\學習資料整理\\C++資料\\test.txt", "a+") != 0){cout << "文件打開失敗" << endl;}string str = "C++\n";fprintf_s(file, str.c_str());return 0;
}
2.2、讀文件
2.2.1、fgets
逐行讀取文件
#include<iostream>
#include<string>
using namespace std;
int main()
{FILE* file;fopen_s(&file,"D:\\學習資料整理\\C++資料\\test.txt", "r+");if (file == NULL){cout << "文件不存在" << endl;return 0;}while (!feof(file)){char content[100];// 注意這里,使用fgets時,最后一行也會檢查,返回NULL// 如果不判斷的話,最后一行還會輸出一次if (fgets(content, 100, file) == NULL)break;cout << content << endl;}
}
2.2.2、fscanf
#include<iostream>
#include<string>
using namespace std;
int main()
{FILE* file;if (fopen_s(&file, "D:\\學習資料整理\\C++資料\\test.txt", "a+") != 0){cout << "文件打開失敗" << endl;}char str1[100];char str2[100];int num;// 將文件指針移到文件頭rewind(file);int counter = fscanf(file, "%s %s %d", str1, str2, &num);cout << str1 << " " << str2 << " " << num;
}
總結