我是C的新手,我编写了一个收集学生数据的代码,但我遇到的问题很少。它没有读取文件,其次,当我尝试追加时,新数据没有添加到新行。我究竟做错了什么?
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int giveChoiceForFileOpenType();
void WriteFile();
void ReadFile();
void ApendFile();
void printChoices();
int openFileFromConsole(FILE *fp1);
void saveStudentGradeInfoTofile(FILE *fp1);
typedef struct student {
char name[50];
char id [20];
int score;
}student;
int main() {
printChoices();
int choice = giveChoiceForFileOpenType();
switch(choice){
case 1: WriteFile();
break;
case 2: ReadFile();
break;
case 3: ApendFile();
break;
default: printf("Error!!!\n");
}
return 0;
}
void WriteFile(){
FILE *fp1 =fopen("E://registry.csv", "w");
openFileFromConsole(fp1);
saveStudentGradeInfoTofile(fp1);
fclose(fp1);
}
void ReadFile(){
FILE *fp2 = fopen("E://registry.csv", "r");
openFileFromConsole(fp2);
fclose(fp2);
}
void ApendFile(){
FILE *fp3 = fopen("E://registry.csv", "a");
openFileFromConsole(fp3);
saveStudentGradeInfoTofile(fp3);
fclose(fp3);
}
void printChoices(){
printf("1.Write\n");
printf("2.Read\n");
printf("3.Append\n");
return;
}
int giveChoiceForFileOpenType(){
int choice;
printf("Select fileopen type:");
scanf("%d",&choice);
return choice;
}
int openFileFromConsole(FILE *fp1){
if(fp1 == NULL )
{
printf("Error!");
return 0;
}
return 1 ;
}
void readingDataFromFile(){
}
void saveStudentGradeInfoTofile(FILE *fp1)
{
int numOfStudent ;
student s[100];
printf ("Get the number of students :");
scanf("%d",&numOfStudent);
for(int i = 0; i < numOfStudent; i++) {
printf("\nEnter ID number:");
scanf(" %s",s[i].id);
printf("Enter name: ");
scanf("%s,",s[i].name);
printf("Enter score: ");
scanf("%d",&s[i].score);
fprintf(fp1,"%s, %s, %d",s[i].id,s[i].name,s[i].score);
printf("\n");
}
}
答案 0 :(得分:1)
如果您想将输出放在单独的行上,则需要在格式字符串中添加\n
字符,如下所示
fprintf(fp1,"%s, %s, %d\n",s[i].id,s[i].name,s[i].score);
答案 1 :(得分:1)
我确信如果我在这里不正确,有人会纠正我,但是一旦你使用了fopen
,你看起来就不会对文件做任何事了。
当你致电ReadFile()
时,它使用fopen
文件名并处于阅读模式,这很好。然后它调用openFileFromConsole(fp2)
,但是该函数对调用函数执行return 1
,然后关闭文件。
如果我错过了某些东西,我相信有人会纠正。