gpt4 book ai didi

c - 文件无法在 C 中正确保存

转载 作者:行者123 更新时间:2023-11-30 21:06:13 25 4
gpt4 key购买 nike

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

#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---

最佳答案

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

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

关于c - 文件无法在 C 中正确保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com