fopen returns non-null pointer even though file does not exist

-2

I have a Hex file whose contents are like below:

0x14000800 0x52100000 0xD503201F 0xD503201F 0x0030A308 0x0032D138 0x00000000 0x00000000 0x00000000 0x00000000

I need to open and read this file. Below is my code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
 char ch, boot_rom_golden[16];
 FILE *myFile = NULL;

 myFile = fopen("/prj/vlsi/tests/boot_rom_fail/src/apps_proc0/sm6140_rom.a52100000_ROM_FULL.hex", "r");

 if (myFile == NULL) {
    printf("Error Reading File\n");
    exit(0);
  }

while ((ch = fgetc(myFile)) != EOF) {
printf("%x \n", ch);
}

I have two questions:

  1. My understanding is if the file does not exist in the above mentioned path, then fopen should return a NULL. Observation is : even if the file does not exist in the above path (/prj/vlsi/....) , fopen is returning some value and then it goes to while loop trying to print the content. Why is this happening? My main.c and the hex file are residing in the same path. But still I tried giving the complete path which also gave the same results (i.e. even if file does not exist it is returning a non zero pointer value)

  2. When the code executes while loop, it prints "FF" indefinitely. It should be because of reason stated above.

Please help to know the issue and how to debug these kind of issues ?

c
file
asked on Stack Overflow Dec 26, 2018 by user3565150 • edited Dec 26, 2018 by CinCout

2 Answers

1

Use an int instead of a char for ch

1) Because fgetc returns an int

The C library function int fgetc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream.

2) Because EOF can be defined as some number not representable by char

Same for boot_rom_golden

answered on Stack Overflow Dec 26, 2018 by David Ranieri • edited Dec 26, 2018 by David Ranieri
0

When I compile and run your code on my system it behaves as you would expect: myFile becomes a null pointer and the null test causes an early exit. On your machine, myFile == NULL is not true, and the early exit does not occur.

I deduce that either the code you are actually executing is not the same as the code you posted, or there is something going on in your environment that is different from mine.

Can you trace through this line by line?

Are you certain that the file named does not exist on your system at the moment this is being executed?

Perhaps there is truncation occurring? Try a short path and short filename.

Try an absolute filepath rather than a relative one.

Null is likely a macro -- perhaps it's not what you think? Try if(myFile) as an alternate.

If not resolved, post more info about your system, and tell us what myFile is when your system does not think it's equal to NULL.

answered on Stack Overflow Dec 26, 2018 by Craig.Feied

User contributions licensed under CC BY-SA 3.0