我不想读取一个文件(每一行中有10K个浮点数(,并找到它的max_val元素(我现在还不远(。我设法将文件放入一个char数组,但我需要它是一个float数组才能找到最大值。
谢谢你的帮助。
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]){
char nameDatei[100];
if(argv[1] != NULL) {
strcpy(nameDatei, argv[1]);
} else {
printf("type in the name of the file: ");
scanf("%s", nameDatei);
}
//read file;
FILE *fPointer;
fPointer = fopen("findMaxOfFloats.txt", "r");
//save
char singleLine[100];
char content[10000][100];
int i = 0;
while (!feof(fPointer)){
if (fgets(content[i], sizeof(singleLine), fPointer) != NULL)
i++;
}
fclose(fPointer);
//print the array
for(int loop = 0; loop < 10000; loop++){
printf("%s", content[loop]);
}
//find max...
return 0;
}
一些问题。。。
- 您将一行读取到
singleLine
中,但不将其复制到content
中 feof
坏——只需检查fgets
的返回值- 您希望
content
是double
,而不仅仅是char
数组 - 执行
fgets
之后,您可以/应该使用strtod
将singleLine
中的字符串转换为二进制/浮点值 - 您希望保留读取的行数计数(即
content
中的有效元素数( - 您从
argv[1]
或scanf
中获取文件名,但随后使用硬连接的名称 - 您没有检查
fopen
的返回值
这是重构后的代码。注释:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCONTENT 10000
int
main(int argc, char *argv[])
{
char nameDatei[100];
if (argv[1] != NULL) {
strcpy(nameDatei, argv[1]);
}
else {
printf("type in the name of the file: ");
scanf("%s", nameDatei);
}
// read file;
FILE *fPointer;
// NOTE/BUG: You get a filename from either argv[1] or scanf but don't use it
#if 0
fPointer = fopen("findMaxOfFloats.txt", "r");
#else
fPointer = fopen(nameDatei, "r");
if (fPointer == NULL) {
perror(nameDatei);
exit(1);
}
#endif
// save
char singleLine[100];
#if 0
char content[10000][100];
#else
double content[MAXCONTENT];
#endif
#if 0
int i = 0;
while (!feof(fPointer)) {
if (fgets(content[i], sizeof(singleLine), fPointer) != NULL)
i++;
}
#else
int count = 0;
// read in all lines until EOF
while (fgets(singleLine,sizeof(singleLine),fPointer) != NULL) {
// don't overflow the array
if (count >= MAXCONTENT) {
printf("count too largen");
exit(1);
}
// decode the number
char *cp;
content[count] = strtod(singleLine,&cp);
// check for syntax error
if (*cp != 'n') {
printf("syntax error: %s",singleLine);
exit(1);
}
++count;
}
#endif
fclose(fPointer);
// print the array
for (int idx = 0; idx < count; ++idx)
printf("%gn", content[idx]);
// find max... [and min, too ;-)]
double max = content[0];
double min = content[0];
for (int idx = 0; idx < count; ++idx) {
// get the current value
double cur = content[idx];
// set new maximum
if (cur > max)
max = cur;
// set new minimum
if (cur < min)
min = cur;
}
printf("min=%g max=%gn",min,max);
return 0;
}
在上面的代码中,我使用了cpp
条件词来表示旧代码与新代码:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
注意:这可以通过unifdef -k
运行文件来清除