-
File input problem
I wrote a simple program called "processor.c" like this:
Code:
#include <stdio.h>
#include "memory.h"
#include "processor.h"
#include "Instructions.h"
int main()
{
char * fileName = "data.txt";
int flag = loadFile( fileName );
if(flag>0)
execute();
return 0;
}
int loadFile( char * fileName )
{
FILE * fPointer;
int line = 0;
int data = 0;
fPointer = fopen( fileName, "r" );
if ( fPointer == NULL )
{
printf( "File could not be opened\n" );
return -1;
}
else
{
while ( !feof( fPointer ) )
{
fscanf( fPointer, "%d", & data );
memory[line] = data;
++line;
}
return 1;
}
}
I have saved my "data.txt" under the same directry with "processor.c". there is no compile errors or run time errors. However, when I run it, the "fOpen" method, could never open the file, it always returns the null back to "fPointer". So the result always ends up with a printing statement:"File could not be opened". I just can't see why it is so??? Could anybody help me on this. Thank you very much for the help.
-
Use perror instead of printf for more details on why the file couldn't be opened.
Code:
perror("File could not be opened");
Most likely the file couldn't be found because it's in the wrong directory.
>while ( !feof( fPointer ) )
This is going to bite you eventually. feof was not designed to be used as a loop condition. A better approach would be to use the return value of your input function as the condition.
Code:
while ( fscanf( fPointer, "%d", & data ) == 1 )
{
memory[line] = data;
++line;
}