文件未在 C 中正确保存

File not saving properly in C

我遇到的问题是数据没有正确存储, 我想要的是无论您何时 运行 代码,它仍然拥有信息。 这是我遇到问题的代码:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
typedef struct{
int select;
char NoteNames[20];
char NoteTexts[200];
}Notes;
char Input[20];
bool RUN = true;
#define ARRAYLEN 2
Notes a[ARRAYLEN];
int main(void) {
    int i;
  FILE *fp;
  while(RUN == true){
  printf("\nWould you like to view notes or take notes?\n<view/take/leave>\n");
  scanf("%s",Input);
  if (strncmp(Input, "view",1)==0){
    fp = fopen ("Notes.dat", "a+");
    printf("Here are the notes\n\n");
    for(i=0; i<(ARRAYLEN-1); i++){
        fread(&a[i], sizeof(a), 1, fp );
        printf("%s : %s \n",a[i].NoteNames,a[i].NoteTexts);
    }
    fclose(fp);
  }
  if (strncmp(Input, "take",1)==0){
    fp = fopen ("Notes.dat", "a");
    printf("\nNote name : ");
    scanf("%s",a[i].NoteNames);
    printf("\nNote text : ");
    scanf("%s",a[i].NoteTexts);
    fclose(fp);
  }
  if (strncmp(Input, "leave",1)==0){
    RUN = false;
  }
  }
  return 0;
}

我试过更改 fopen 类型(即 r/r+ a/a+),但我无法找出代码有什么问题。 抱歉,如果我做的完全错了,这主要是我在互联网上找到的代码不匹配 xD。

编辑: 输出一切正常,和我期待的一样,但是像我说的问题是数据没有被保存。

---HERE IS WHAT IT OUTPUTS---
Would you like to view notes or take notes?
<view/take/leave>
 take
Enter the notes name:
 lol
Enter the notes text:
 kek
Would you like to view notes or take notes?
<view/take/leave>
 view
lol : kek
Would you like to view notes or take notes?
<view/take/leave>
leave
>
---NEXT RUN---
Would you like to view notes or take notes?
<view/take/leave>
view
 : 
Would you like to view notes or take notes?
<view/take/leave>
---END OF OUTPUT---

仔细阅读您的代码并逐行检查:

  • 在第一个 if 中,您打开、读取和关闭文件。
  • 在第二个 if 中,您只需打开然后关闭文件。
    • 没有写入。

使用 fprintf 将您的内容写入文件。

您可以使用以下代码写入文件

FILE *fptr;
fptr = fopen("program.txt", "w");
if(fptr == NULL)
{ 
printf("Error!");
exit(1);
} 
printf("Enter a sentence:\n");
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);

还有 按以下阅读文件

char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) 
{
printf("Error! opening file");
//Program exits if file pointer returns NULL. 
exit(1);
} 
// reads text until newline fscanf(fptr,"%[^\n]", c); 
printf("Data from the file:\n%s", c); 
fclose(fptr);