1

I'm currently trying to create a database in C, using a .txt document as the place to store all the data. But I can't get fputs() to shift line, so everything that my program writes in this .txt document is only on one line.

    int main(void){

   char c[1000];
   FILE *fptr;
   if ((fptr=fopen("data.txt","r"))==NULL){
       printf("Did not find file, creating new\n");
       fptr = fopen("data.txt", "wb"); 
       fputs("//This text file contain information regarding the program 'monies.c'.\n",fptr);
       fputs("//This text file contain information regarding the program 'monies.c'.\n",fptr);
       fputs("//Feel free to edit the file as you please.",fptr);
       fputs("'\n'",fptr);
       fputs("(Y) // Y/N - Yes or No, if you want to use this as a database",fptr);
       fputs("sum = 2000 //how much money there is, feel free to edit this number as you please.",fptr);
       fclose(fptr);


   }
   fscanf(fptr,"%[^\n]",c);
   printf("Data from file:\n%s",c);

   fclose(fptr);
   return 0;
}

This is my testing document. I feel like I've tried everything and then some, but can't get it to change line, help is much appreciated. Btw. The output looks like this: Output from the program.

Asger Weirsøe
  • 350
  • 1
  • 11

1 Answers1

4

There are two issues in your program :

  • You should specify "w" rather than "wb" so that the file is read and written as text rather than binary. Although in some systems this makes no difference and b is ignored.
  • The part for file reading should be in an else, otherwise it executes after file creation with fptr not containing a valid value.

This is the code with those corrections. I do get a multiline data.txt with it.

int main(void){

  char c[1000];
  FILE *fptr;
  if ((fptr=fopen("data.txt","r"))==NULL){
     printf("Did not find file, creating new\n");
     fptr = fopen("data.txt", "w");
     fputs("//This text file contain information regarding the program 'mon
     fputs("//This text file contain information regarding the program 'mon
     fputs("//Feel free to edit the file as you please.",fptr);
     fputs("'\n'",fptr);
     fputs("(Y) // Y/N - Yes or No, if you want to use this as a database",
     fputs("sum = 2000 //how much money there is, feel free to edit this nu
     fclose(fptr);
  }
  else
  {
    fscanf(fptr,"%[^\n]",c);
    printf("Data from file:\n%s",c);
    fclose(fptr);
  }
  return 0;
}
Anonymous Coward
  • 3,140
  • 22
  • 39
  • 1
    "wt" is a non-standard mode for an `fopen()` call. See 7.19.5.3: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf – Andrew Henle Oct 14 '15 at 09:42