I have a simple file reading algorithm but it's not returning the values that are in the file. The below is the code. The input txt values are 200 53 65 98 183 37 122 14 124 65 67 but the code is returning 48 48 32 53 51 32 54 53 32 57 56 32 49 56 51 32 51 55 32 49 50 50 32 49 52 32 49 50 52 32 54 53 32 54 55 -1 and I'm not sure why.
It should be taking the read in values and putting it into the linked list.
int readInputFile(char *fileName, LinkedList *list)
{
FILE *inputFile = fopen(fileName, "r");
int ch;
if (inputFile == NULL)
{
perror("Could not open file");
}
else
{
while (ch != EOF)
{
ch = fgetc(inputFile);
printf("%d", ch);
if (ferror(inputFile))
{
perror("Error reading from source file.");
}
else
{
//printf("%d", ch);
insertLast(list, ch);
}
}
}
}
CodePudding user response:
Your code has undefined behavior because you test while (ch != EOF)
with ch
uninitialized the first time. You should write:
while ((ch = fgetc(inputFile)) != EOF) {
[...]
Yet the problem is you read individual bytes instead of parsing the file contents for numbers expressed as decimal integers. You should use fscanf()
to convert the text into integers.
You also forgot to close the file, causing resource leakage.
Here is a modified version:
int readInputFile(const char *fileName, LinkedList *list)
{
FILE *inputFile = fopen(fileName, "r");
if (inputFile == NULL) {
perror("Could not open file");
return -1;
} else {
int value, count = 0;
char ch;
while (fscanf(inputFile, "%d", &value) == 1) {
printf("inserting %d\n", value);
insertLast(list, value);
count ;
}
if (fscanf(inputFile, " %c", &ch) == 1) {
fprintf(stderr, "File has extra bytes\n");
}
fclose(inputFile);
return count; // return the number of integers inserted.
}
}
CodePudding user response:
You read a character with fgetc()
but you want to read a number which you do with int d; fscanf(inputFile, "%d", &d)
.