从文本文件中删除数据(c编程)

时间:2014-08-02 10:51:05

标签: c

我用c编程编程 它用于为学生添加(姓名,TP,国籍,性别,年龄)等信息 并且喜欢删除等一些功能 对于删除部分,我将信息移动到另一个文件,除了我选择的学生或我键入他要删除的TP号码。 但是阅读部分有问题所以它不会删除

void add ()


e = fopen_s(&f,"student.txt","a+");
int studentcount ;
printf("pelase enter how many students u want to add");
scanf("%d",&studentcount);
if(e!=0)
{
    printf("File could not be created.");
    exit(1);
}
for(i = 0; i<studentcount;i++)
{
    fflush(stdin);
    printf("\nPlease enter the student name : ");
    gets(name);
    printf("\nPlease enter the student nationality : ");
    gets(nationality);
    printf("\nPlease enter the student gender : ");
    gets(gender);
    printf("\nPlease enter the student age : ");
    scanf("%d", &age);
    printf("\nPlease enter the TP number : ");
    scanf("%d", &TP);
    printf("\nPlease enter the student contact number : ");
    scanf("%d", &contact);
    fprintf(f,"%i\t %s\t %s\t %s\t %d\t ;%d;\t %d\n",strlen(name), name, nationality, gender, age, TP,contact);
}


fclose(f);

main();

删除功能

    FILE *originalfile =  fopen ("student.txt","r");

    int deltp, temp = 1;
    char c;
    c = getc (originalfile);
    while (c !=EOF)
    {
    printf ("%c",c);
    c = getc(originalfile);

    }
    rewind(originalfile);

    printf ("%c",c);
    printf ("please enter the student TP\n");
    scanf ("%d",&deltp);
    FILE *newfile =  fopen ("student_temp.txt","w");
    c = getc (originalfile);
while (c !=EOF)
    {c = getc (originalfile);
    if (c == '\n')
    temp++;
    if (c != deltp)
    {
            fputc (c,newfile);
    }
    }


    fclose(originalfile);
    fclose(newfile);

printf("student has been deleted\n");   
printf("\n The contents of file after being modified are as follows:\n");
newfile = fopen("student_temp.txt", "r");
c = getc(newfile);
while (c != EOF)
{
    printf("%c", c);
    c = getc(newfile);
}
fclose(newfile);

            main();
}

1 个答案:

答案 0 :(得分:0)

您以哪种格式打印到以相同格式读取的文件中。那么这很容易做到。

add()函数fprintf中进行以下更改。因此,当使用delete阅读fscanf时,这将很容易

fprintf(f,"%i\t %s\t %s\t %s\t %d\t %d\t %d\n",strlen(name), name, nationality, gender, age, TP,contact); // don't use semi colon in between

而不是这个逻辑 -

c = getc (originalfile);
while (c !=EOF)
{
     c = getc (originalfile);
     if (c == '\n')
     temp++;
     if (c != deltp)
     {
        fputc (c,newfile);
     }
}

使用此逻辑 -

int len;
printf ("please enter the student TP\n");
scanf ("%d",&deltp);
FILE *newfile =  fopen ("student_temp.txt","w");
while((fscanf(originalfile,"%i %s %s %s %d %d %d",&len, name, nationality, &gender, age, &TP, &contact))!=EOF){
    if(deltp != TP)
    fprintf(newfile,"%i\t %s\t %s\t %s\t %d\t ;%d;\t %d\n",strlen(name), name, nationality, gender, age, TP,contact);
}
fclose(newfile);
fclose(originalfile);

希望这会对你有帮助!