1

我目前正在尝试在 C 中创建一个数据库,使用 .txt 文档作为存储所有数据的地方。但是我不能让 fputs() 换行,所以我的程序在这个 .txt 文档中写入的所有内容都只在一行上。

    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;
}

这是我的测试文档。我觉得我已经尝试了一切,然后又尝试了一些,但无法改变线路,非常感谢帮助。顺便提一句。输出如下所示: 程序的输出。

4

1 回答 1

4

您的程序中有两个问题:

  • 您应该指定“w”而不是“wb”,以便文件以文本而不是二进制形式读取和写入。尽管在某些系统中这没有区别,并且 b 被忽略。
  • 文件读取部分应该在else中,否则在文件创建后执行,fptr不包含有效值。

这是带有这些更正的代码。我确实得到了一个多行 data.txt 。

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;
}
于 2015-10-14T09:39:44.630 回答