从文件中读数据,直接写入 std::vector
时间: 2023-07-26 20:36:12 浏览: 54
好的,你可以使用 C++ 中的 ifstream 类来打开文件并读取数据,然后将数据存储到 std::vector 中。下面是一个示例代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::ifstream infile("data.txt");
std::vector<int> data;
int temp;
while (infile >> temp) {
data.push_back(temp);
}
for (int i = 0; i < data.size(); ++i) {
std::cout << data[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
在上述代码中,我们使用 std::ifstream 打开名为 "data.txt" 的文件。然后,我们创建一个 std::vector 对象并将数据逐个读入,并将其插入到 std::vector 中。最后,我们遍历 std::vector 并将其内容输出到控制台。
相关问题
fwrite 写入 std::vector<int>
可以使用 fwrite() 函数将 std::vector<int> 中的数据写入文件。假设需要将 vector 写入的文件名为 data.bin,代码如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> data = {1, 2, 3, 4, 5};
FILE *fp = fopen("data.bin", "wb");
if (fp != NULL) {
fwrite(&data[0], sizeof(int), data.size(), fp);
fclose(fp);
}
return 0;
}
```
在上面的代码中,先创建一个 std::vector<int>,然后以二进制写方式("wb")打开一个名为 data.bin 的文件,接着使用 fwrite() 函数将 vector 中的数据写入文件。注意,需要将 vector 的数据首地址传递给 fwrite() 函数,即 &data[0]。
需要注意的是,由于 fwrite() 函数是将连续的内存块写入文件,因此在写入 vector 时,需要保证 vector 中的数据是连续的。如果 vector 中的数据不是连续的,可以使用 std::array<int, N> 等连续的容器来代替 vector。
std::vector<uint8_t>数据写入文件
可以使用文件流和迭代器来实现将 std::vector<uint8_t> 写入文件的操作,示例如下:
```c++
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::vector<uint8_t> data = {0x12, 0x34, 0x56, 0x78};
std::ofstream fout("data.bin", std::ios::binary);
if (!fout.is_open()) {
std::cerr << "Failed to open file!" << std::endl;
return -1;
}
std::copy(data.begin(), data.end(), std::ostreambuf_iterator<char>(fout));
fout.close();
return 0;
}
```
在上述代码中,使用 `std::ofstream` 打开文件,并指定以二进制模式打开,然后使用 `std::copy` 将 vector 中的数据复制到文件中。最后关闭文件。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)