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

问题描述:

#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; 
    } 

} 

文件我想读的是:如何使用fread和缓冲从C++文件中读取文件?

20 
10 
7 
19 
20 
19 
7 
1 
1 
514 
8 
5665 
10 
20 
17 
16 
20 
17 
20 
2 
16 

我想被存储在变量天,这是数组的塔尺寸,以及阵列中其他部分的第一,但它读取一切只是最后一个号码。 每个号码都在一个新行中。我可以改变一下吗?我正在考虑最后一个条件。谢谢

+0

除了'使用命名空间标准;'丑陋的一些cout,问题不是C++,请标记它C – 2015-02-17 20:49:34

+0

在C++中,我建议使用'std :: istream :: read'到一个'std :: vector '或者'std :: string'。您可以使用'std :: istringstream'来读取矢量,就好像矢量是输入流一样。不需要您使用动态内存。 – 2015-02-17 20:51:55

+0

在“从文件整数读取C++”或“从文件数组读取C++”中搜索StackOverflow。 – 2015-02-17 20:53:47

如果您要编写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是可选的 - 主要是存在,表明我们期望我们读到的第一个数字来匹配我们从阅读其他项目的数量文件。