Thread: Read() problems

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    1

    Read() problems

    I am writing an emulator that uses read() to load the contents of a file into an array:
    Code:
    int load_roms(unsigned char userom[])
    {
    	FILE *romfile; /* Create pointer to ROM file */
    	romfile=fopen(userom,"r"); /* Load apple.rom read-only */
    	if (!romfile) /* Check for problems opening the file */
    	{
    		printf("Cannot read %s \n", userom);
    		return 1;
    	}
    	int errcheck = read(romfile, &memory[0xF000], 1024); 
    	if(errcheck = -1)
    	{
    		printf("ROM-File read error \n");
    	}
    	else printf("Bytes Read: %i \n", errcheck);
    	
    	fclose(romfile); /*Close romfile */
    	return 0;
    }
    Whenever I run it, however, read() returns -1! What am I doing wrong?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Should it be fread when the file is opened with fopen and read when the file is opened with open?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > romfile=fopen(userom,"r");
    You might want "rb", since this is binary data

    > int errcheck = read(romfile, &memory[0xF000], 1024);
    Normal C doesn't allow declarations in the middle of statements.
    You're either using an extension to your compiler, a C99 compiler (still pretty rare) or a C++ compiler.

    > if(errcheck = -1)
    A classic trap - this is an assignment, not a comparison.

    If gcc is your compiler, then the -Wall option would have detected this.
    Other compilers with sensitive warning options also detect this.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. read only folder on Windows
    By George2 in forum Windows Programming
    Replies: 2
    Last Post: 11-05-2007, 09:18 AM
  2. read in csv file
    By gums in forum C Programming
    Replies: 5
    Last Post: 05-10-2007, 07:38 AM
  3. fread problems
    By Happy_Reaper in forum C Programming
    Replies: 4
    Last Post: 03-15-2006, 10:27 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Replies: 1
    Last Post: 07-24-2002, 06:33 AM