c++如何读取txt文件
时间: 2023-10-05 09:10:20 浏览: 26
您可以使用文件输入流来读取txt文件。以下是一个简单的例子:
```c
#include <stdio.h>
int main()
{
FILE *fp;
char buffer[100];
fp = fopen("file.txt", "r");
if (fp == NULL)
{
printf("Error: failed to open file.\n");
return -1;
}
fgets(buffer, 100, fp);
printf("Read from file: %s\n", buffer);
fclose(fp);
return 0;
}
```
在这个例子中,我们打开一个名为"file.txt"的文件,并使用fgets函数从文件中读取一行内容并将其存储到一个字符串缓冲区中。最后,关闭文件并输出读取到的内容。
相关问题
c++ 读取txt文件
可以使用C++中的fstream库来读取txt文件,并将其存入string中。具体步骤如下:
1. 引入头文件
```c++
#include <fstream>
#include <string>
```
2. 打开文件
```c++
std::ifstream file("filename.txt");
```
3. 读取文件内容
```c++
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
```
4. 关闭文件
```c++
file.close();
```
完整代码如下:
```c++
#include <fstream>
#include <string>
int main() {
std::ifstream file("filename.txt");
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
return ;
}
```
c++读取txt文件数据
以下是使用C++读取txt文件数据的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt"); // 打开文件
std::string line;
if (file.is_open()) {
while (getline(file, line)) { // 逐行读取文件内容
std::cout << line << std::endl; // 输出每行内容
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std::endl;
}
return 0;
}
```
这段代码首先使用`ifstream`类打开名为"example.txt"的文件。然后,使用`getline`函数逐行读取文件内容,并将每行内容存储在`line`字符串中。最后,通过`cout`语句将每行内容输出到控制台。如果无法打开文件,则会输出"无法打开文件"。