c语言:将文件内容读取为数字并将它们加在一起 [英] c language : read file content as numbers and add them together
问题描述
我的文本文件中包含以下内容:values.txt
I have the following in a text file called: values.txt
1 4
2.5 3.76
122 10
277.543
165.4432
我正在尝试读取此文本文件的内容,并将每两对加在一起并输出结果... 输出将是这样的:
I am trying to read the content of this text file, and add each two pairs together and output the result ... the output would be something like this :
1 Pair:(1, 4) = 5
2 Pair:(2.5, 3.76)= 6.26
以此类推..
我正在打开这样的文件
int c;
FILE myfile;
myfile= fopen("values.txt", "r");
if ( myfile == NULL ) {
printf("Cannot open TEXT file\n");
return 1;
}
double aa,bb;
while ( (c = getc(myfile) ) != EOF ) {
// HERE SHOULD I DO THE OUTPUT BUT HOW?
}
我们非常感谢您的帮助.
Any help is really appreciated ..
语言= C
推荐答案
以下代码可以实现您所期望的. myfile应该声明为FILE *. fopen返回一个指向FILE结构的指针.如果文件很大,我建议读取大尺寸的缓冲区(例如65535等),然后按char解析char并将其转换为float值.与处理文本浮点值相比,它减少了系统调用开销,该过程比处理文本花费更多的时间.
The following code does what you expect. myfile should be declared as FILE*. fopen returns a pointer to FILE structure. If the file is very large, I would recommend reading in buffers of big size (eg: 65535 etc) and parse it char by char and convert it to float values. It reduces system call overhead which takes more time than processing text to float values.
#include <stdio.h>
#include <string.h>
main(int argc, char *argv[])
{
FILE* myfile;
myfile = fopen("values.txt", "r");
if ( myfile == NULL ) {
printf("Cannot open TEXT file\n");
return 1;
}
double aa,bb;
while (2 == fscanf(myfile, "%lf %lf", &aa, &bb)) {
printf("%lf\n", aa+bb);
}
return 0;
}
这篇关于c语言:将文件内容读取为数字并将它们加在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!