0

I have the following snippet of code at the beginning of my program:

printf("Starting extraction of file %s \n", tarName);

// Open the tarFile
FILE* tarFile = fopen(tarName, "r");
if(tarFile == NULL) return EXIT_FAILURE;

// Read nFiles
printf("Reading header...");
...

When I execute it from the terminal I get the following output:

Starting extraction of file test.mytar 

And then the program freezes, apparently never reaching the second printf.

test.mytar is an existing file in the same folder as my executable, and this is the same folder from where I am executing the terminal.

The file was created by me byte a byte, so it could possibly be violating file conventions I am not aware of.

What could possibly be going on here?

Jsevillamol
  • 2,425
  • 2
  • 23
  • 46
  • Add a print statement just after `fopen` and before the if. Is it printed? – Support Ukraine Oct 13 '17 at 10:01
  • You should also show how the function is called and the code executed when the function returns – Support Ukraine Oct 13 '17 at 10:02
  • ... and have a `\n` in **all** `printf` – Support Ukraine Oct 13 '17 at 10:03
  • 1
    @4386427 `\n` flushing the `stdout` buffer is platform-specific. The proper way to ensure the buffer is flushed is to either disable buffering, explicitly set line-buffering, or actually flush it. – Andrew Henle Oct 13 '17 at 10:04
  • @ChrisTurner turns out you are right! I was mistaken on where the bug was due to the confusing flush behavior – Jsevillamol Oct 13 '17 at 10:07
  • 1
    @AndrewHenle For a terminal (which I assume there), I think it does – Support Ukraine Oct 13 '17 at 10:08
  • @4386427 Per **7.21.3 Files**, paragraph 3, of the [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf): "Support for these characteristics is **implementation-defined**, and may be affected via the `setbuf` and `setvbuf` functions." Just because Linux line-buffers `stdout` when it's a terminal doesn't make that a universal truth. – Andrew Henle Oct 13 '17 at 10:20
  • @Jsevillamol running your code in a debugger would have shown you that it went past the `printf` without any problems. – Chris Turner Oct 13 '17 at 10:55

1 Answers1

0

As pointed out in the comments, two things may happen.

a) the fopen fails (IO error, permission denied, missing file, ...). To know the exact cause, you need to print the errno (or GetLastError() on Windows) :

if(tarFile == NULL) {
    printf("%s\n", strerror(errno));
    return EXIT_FAILURE;
}

b) the fopen succeeds but printf("Reading header..."); does not show up anything because the message is buffered and not yet printed. To correct this, you can generally add a '\n' at the end of the message.

user803422
  • 2,636
  • 2
  • 18
  • 36