将文件放入C 中的数组中
put the file into an array in c++
我正在尝试读取txt文件,然后将其放入char数组中。但是,我可以读取包含不同字符的不同文件并将其放入数组中的不同文件。我可以创建一个动态数组以包含未知的字符长度。
您可以将一个未知大小的文件读取为:
的动态数据结构 std::vector
更多信息在这里。
另外,您可以使用new
分配动态内存。但是,矢量至少对我来说更方便:(。
#include <vector>
#include <iostream>
#include <fstream>
int main(int argc, char **argv)
{
std::vector<std::string> content;
if (argc != 2)
{
std::cout << "bad argument" << std::endl;
return 0;
}
std::string file_name (argv[1]);
std::ifstream file(file_name);
if (!file)
{
std::cout << "can't open file" << std::endl;
return 0;
}
std::string line = "";
while (std::getline(file, line))
{
content.push_back(line);
line = "";
}
for (std::vector<std::string>::iterator it = content.begin(); it != content.end(); ++it)
std::cout << *it << std::endl;
}
这是使用std :: vectors and std :: string
的解决方案程序将文件名称为第一个参数,打开它,按行读取IT
每行都写在矢量
中然后,您可以像我在功能末尾一样显示向量
编辑:由于C 11是新的Standars,因此程序使用C 11,因此您必须使用C 11(如果使用G (进行编译(g++ -std=c++11
(
我刚刚测试了它的工作原理
可能有可用的库例程可为您提供文件的大小,而无需阅读文件的内容。在这种情况下,您可以获取大小并分配全尺寸的缓冲区,然后一次吸入整个文件(如果您的缓冲区是一个简单的char数组,请不要忘记添加一个并放入尾随的Nullchary]。/p>
最好的方法是使用malloc()
,realloc()
和free()
,就像它是一个旧的C程序一样。如果您尝试使用std::vector
,您将ch缩在最大rAM上,因为realloc()
可以生长并缩小到位(生长在堆上取决于堆,而std::vector
不能这样做。
特别是:
#include <iostream>
#include <tuple>
// TODO perhaps you want an auto-management class for this tuple.
// I'm not about to type up the whole auto_ptr, shared_ptr, etc.
// Mostly you don't do this enough to have to worry too hard.
std::tuple<char *, size_t> getarray(std::istream &input)
{
size_t fsize = 0;
size_t asize = 0;
size_t offset = 0;
size_t terminator = (size_t)-1;
char *buf = malloc(asize = 8192);
if (!buf) throw std::bad_alloc();
char *btmp;
char shift = 1;
do {
try {
input.read(buf + offset, asize - fsize);
} catch (...) {
free(buf);
throw;
}
if (input.gcount == 0) {
btmp = realloc(buf, bufsize);
if (btmp) buf = btmp;
return std::tuple<char *, size_t>(buf, fsize);
}
offset += input.gcount;
fsize += offset;
if (fsize == asize) {
if (shift) {
if ((asize << 1) == 0)
shift = 0;
else {
btmp = realloc(buf, asize << 1);
if (!btmp)
shift = 0;
else {
asize <<= 1;
buf = btmp;
}
}
if (!shift) {
btmp = realloc(buf, asize += 8192);
if (!btmp) {
free(buf);
throw std::bad_alloc();
}
}
}
}
} while (terminator - offset > fsize);
free(buf);
// Or perhaps something suitable.
throw "File too big to fit in size_t";
}
相关文章:
- 如何将内容数组写入文本文件?
- C++将文本文件中的数据读取到结构数组中
- 将值从二维数组输出到文本文件
- C++数据文件、数组和计算赋值
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何从txt文件中读取多个不同长度的数组?
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- C++编程从外部文本文件定义数组大小
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 将系数存储在头文件的数组中("does not name a type"错误)
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 从文件读取,并写入函数C++中的数组
- 如何从具有两列的.txt文件创建并行数组?
- 读取二维数组文件