如何使用 fread 和缓冲从 C++ 中的文件中读取文件
How to read files from a file in C++ using fread and buffering?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
FILE *in, *out;
using namespace std;
int main(int argc, char** argv)
{
in = fopen("share.in", "r");
int days;
int size;
int offset = 0;
fscanf(in, "%d", &days);
fseek(in, 0L, SEEK_END);
#if defined(_WIN32)
size = ftell(in) - 1;
#elif defined (_WIN64)
size = ftell(in) - 1;
#else
size = ftell(in);
#endif // defined
fseek(in, 0L, SEEK_SET);
char *buffer = (char*) malloc(size + 1);
char *token;
fread(buffer, 1, size, in);
buffer[size] = 'n';
int *values = (int*) malloc(days * sizeof(int));
int i;
while (*buffer != 'n'){
buffer++;
}
buffer++;
cout << days << endl;
cout << endl;
for (i = 0; i < days; i++){
values[i] = 0;
while (*buffer != 'n'){
values[i] = (values[i] * 10) + (*buffer - '0');
buffer++;
}
buffer++;
}
for (int i = 0; i < days; i++){
cout << values[i] << endl;
}
}
我想读取的文件是这样的:
20
10
7
19
20
19
7
1
1
514
8
5665
10
20
17
16
20
17
20
2
16
我希望第一个存储在变量天中,这是数组的大小,其余的存储在数组中,但它读取除最后一个数字之外的所有内容。每个数字都在新行中。我可以改变什么?我在最后一段时间内在想。谢谢
如果你
要写C++,把它写成C++。我会做这样的工作:
std::ifstream in("share.in");
int days;
in >> days;
std::vector<int> data { std::istream_iterator<int>(in),
std::istream_iterator<int>() };
assert(days == data.size());
对于实际代码,assert
是可选的 - 主要是为了表明我们希望我们读取的第一个数字与我们从文件中读取的其他项目的数量相匹配。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量