我遇到的问题是数据存储不正确, 我想要的是,无论何时运行代码,它仍然拥有信息。 以下是我遇到问题的代码:
#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---
答案 0 :(得分:0)
仔细阅读您的代码并逐行完成:
if
中打开,阅读并关闭文件。if
中,您只需打开然后关闭文件即可。
答案 1 :(得分:0)
使用fprintf将您的内容写入您的文件。
答案 2 :(得分:0)
您可以使用以下代码写入文件
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);