简体   繁体   English

如何读取文件行(整​​数)并将A行到B行的总和求和?

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

Say, file1.dat contains: 说,file1.dat包含:

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). 我在尝试编写addNumbers函数以计算从行Begin(变量)到行End(变量)的总数时遇到麻烦。 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. 变量fileRead是传递到函数中的文件对象。

IE 4 child processes, 1000 lines, each process does 250 lines. IE 4子进程有1000行,每个进程有250行。 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;
    }
}

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. 首先是您要尝试使用char *line作为数字。 That isn't going to work. 那是行不通的。 Unlike higher level languages, C will not cast a string to a number. 与高级语言不同,C不会将字符串转换为数字。 You need to do it explicitly, usually with atoi(line) . 您需要显式地执行此操作,通常使用atoi(line)

Your C compiler should have warned you about the type mismatch which suggests you're not running with warnings on. 您的C编译器应该警告您有关类型不匹配的信息,这表明您没有在运行警告的情况下运行。 Most C compilers will not have warnings on by default, you need to turn them on. 大多数C编译器默认情况下不会打开警告,您需要将其打开。 Usually this is with -Wall like cc -Wall -g test.c -o test . 通常这与-Wall例如cc -Wall -g test.c -o test

Next, total += total + line; 接下来, 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). 表示total = total + total + line ,这可能不是您的意思(如果是,则应写明它以便清楚说明)。 I assume you meant total += line . 我认为您的意思是total += line


Putting them together... 放在一起...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM