如何使用 fread 和缓冲从 C++ 中的文件中读取文件

How to read files from a file in C++ using fread and buffering?

本文关键字:文件 读取 C++ 何使用 fread 缓冲      更新时间:2023-10-16
#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是可选的 - 主要是为了表明我们希望我们读取的第一个数字与我们从文件中读取的其他项目的数量相匹配。