-2

I wrote the following code:

void WriteToFile(const char** strings, const char* path, int n)
{
    FILE* fp = fopen(path, "w");
    int i;
    if(fp)
    {
        for(i = 0 ; i < n ; i++)
        {
            puts(strings[i]);
            fprintf(fp, "%s\n", strings[i]);
        }
    }
    else
    {
        printf("Error at writing to file.\n");
        exit(1);
    }

    fclose(fp);
}

I get an error - fp is pointing to NULL - means fopen() didn't work, weird, I printed the path too and it has no \n or something weird in it and it's available in my computer.

user3745476
  • 91
  • 1
  • 1
  • 6
  • Do you have write rights to the file? Step in with a debugger, copy the path, and paste it into notepad's "open" dialog to see if notepad can find the copy-pasted path. – Mooing Duck Jun 26 '14 at 21:33
  • 1
    [fopen sets errno upon failure](http://linux.die.net/man/3/fopen), what's errno set to after the failure? Use [strerror](http://linux.die.net/man/3/strerror) for a text version of the error string. – fvu Jun 26 '14 at 21:34
  • Are you trying to write to the folder without authority? – BLUEPIXY Jun 26 '14 at 21:46

1 Answers1

2

If you don't know why fopen fails, ask the computer to tell you:

fp = fopen(path, "w");
if( fp == NULL ) {
  perror( path );
  exit(1);  /* Or handle error some other way */
}

Error messages belong on stderr, not stdout. Never use printf to write an error message (use fprintf( stderr, ... instead). perror not only prints the error message to the right place, it also tells you what the problem is.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Out of curiosity, I've always been told the same thing about stderr, but aren't stderr and stdout by default the same thing (i.e., they both output to the console)? Unless you've explicitly set stderr and stdout to something else then, it shouldn't matter, right? – wolfPack88 Jun 26 '14 at 21:39
  • @wolfPack88 that's up to the end user to decide. And if they pipe stderr to somewhere else than the default tty, they expect to see your errors there, and not mangled up between normal outputs they just tried to sift. – Quentin Jun 26 '14 at 22:42
  • Consider the case of running the output of some command through grep: `sort foo | grep bar`. If sort is unable to open the file foo and writes the error to stdout, then (unless the error message contains the string "bar") the error message would be suppressed. – William Pursell Jun 27 '14 at 05:43
  • it prints out '(null)', really weird. – user3745476 Jun 27 '14 at 08:19