user3697365
user3697365

Reputation: 61

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

}

The file I want to read is this:

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

I want the first to be stored in the variable days which is tha size of the array, and the rest in the array, but it reads everything but the last number. Each number is in an new line. What can I change about it? I am thinking sth in the last while condition. Thank you

Upvotes: 0

Views: 1141

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490008

If you're going to write C++, write it as C++. I'd do the job something like this:

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());

For real code, the assert is optional--primarily there to show that we expect the first number we read to match the number of other items we read from the file.

Upvotes: 4

Related Questions