Thread: File input problem

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    6

    Unhappy 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.

  2. #2
    Registered User
    Join Date
    May 2004
    Posts
    127
    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;
    }
    When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File Writing Problem
    By polskash in forum C Programming
    Replies: 3
    Last Post: 02-13-2009, 10:47 AM
  2. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 02:20 PM
  3. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  4. file input output problem..
    By epidemic in forum C++ Programming
    Replies: 10
    Last Post: 12-03-2006, 03:55 AM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM