user1450005
user1450005

Reputation: 53

File is opened but not written to

I read many sites, tried all possible solutions, but code opens the file, but doesnt write the fprintf line, any help is appreciated

int Function(){
  FILE *outputtfilepointer;

  outputtfilepointer = fopen("output.csv", "w"); 
  fprintf(outputtfilepointer,"Iteration,5,6,%d,%f\n",5,0.6);    

  fclose (outputtfilepointer);
  return 0;
}

Upvotes: 0

Views: 86

Answers (1)

Did you read the documentation of fopen(3) and of fprintf(3)? These functions could fail, and you should test that:

int Function(){
  FILE *outputtfilepointer = fopen("output.csv", "w"); 
  if (!outputfilepointer) { perror("fopen"); exit(EXIT_FAILURE); };
  if (fprintf(outputtfilepointer,"Iteration,5,6,%d,%f\n",5,0.6)<0)
     { perror("fprintf"); exit(EXIT_FAILURE); };  
  if (fclose (outputtfilepointer)) 
     { perror("fclose"); exit(EXIT_FAILURE);}
  return 0; 
}

Testing failure of fopen is required (that does happen easily). Many people (me included) are lame so don't bother testing failure of fprintf and fclose, since it is less common.

You'll need a #include <stdlib.h> for exit

Of course, read the documentation of every function that you are using, e.g. also fclose(3), perror(3), exit(3)

Notice the minimal pattern to handle error cases: print using perror (to stderr) an errno related message then exit. Many serious programs are doing more sophisticated things (e.g. using strerror(errno) and longjmp in some error handler ...)

BTW, you should compile with all warnings and debug info (e.g. gcc -Wall -g) and use the debugger (gdb). On Linux you might also use valgrind, strace(1), ltrace(1)

Upvotes: 1

Related Questions