A few issues ...
- You read a line into
singleLine
but don't copy it into content
feof
is bad--just check the fgets
return value
- You want
content
to be double
and not just a char
array.
- After doing
fgets
, you can/should use strtod
to convert the string in singleLine
into a binary/floating point value.
- You want to maintain a count of the number of lines read (i.e. the number of valid elements in
content
).
- You get a filename from either
argv[1]
or scanf
but then use a hardwired name instead.
- You don't check the return value of
fopen
Here is the refactored code. It is annotated:
#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 large\n");
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("%g\n", 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=%g\n",min,max);
return 0;
}
In the above code, I've used cpp
conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k