Search code examples
cscanffseek

How can I read a file line (integer) and sum the total from line A to line B?


Say, file1.dat contains:

123
545
3576
3453
345
34
...
123     //1000th line

I am having trouble trying to write the addNumbers function to calculate the total from line Begin (variable) to line End (variable). Each child process/pipe is to calculate its own portion of the file, adding each partial sum into a final total and printing that total.

Variable fileRead is a file object that is passed into the function.

I. E. 4 child processes, 1000 lines, each process does 250 lines. Here is my working code. Any questions please ask.:

division = numberOfLines/numberOfPipes;
int begin = currentPipe*division;
int end = begin + division;

for(i=begin; i<end; i++)
{
    fseek(fileRead, begin, SEEK_CUR);
    while(fgets(line,sizeof line,fileRead)!= NULL)
    {
    total+= total + line;
    }
}

Solution

  • The problem... several problems, are here:

    while(fgets(line,sizeof line,fileRead)!= NULL)
    {
        total += total + line;
    }
    

    First is you're trying to use char *line as a number. That isn't going to work. Unlike higher level languages, C will not cast a string to a number. You need to do it explicitly, usually with atoi(line).

    Your C compiler should have warned you about the type mismatch which suggests you're not running with warnings on. Most C compilers will not have warnings on by default, you need to turn them on. Usually this is with -Wall like cc -Wall -g test.c -o test.

    Next, total += total + line; means total = total + total + line and that's probably not what you meant (and if it is, you should write it out longhand to make that clear). I assume you meant total += line.


    Putting them together...

    while(fgets(line, sizeof(line), fileRead)!= NULL) {
        total += atoi(line);
    }