C语言 C 语言 - 使用文件 IO、结构、函数、数组、指针在文本文件中记录数据(添加、删除)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18421619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:15:33  来源:igfitidea点击:

C language - record data (add,delete) in text file using file IO, structure, function, array, pointers

cfile-iotext-files

提问by Nabil Fikri

I'm still learning intro to C language. Currently I'm having problem with my code. The task is to ask user to input information about staff and write them into a text file. The problem occur when:

我还在学习 C 语言的介绍。目前我的代码有问题。任务是要求用户输入有关员工的信息并将其写入文本文件。问题发生在:

1) output in text/.exe file display random characters.

1) 在 text/.exe 文件中输出显示随机字符。

2) a new output will overwrite the existing information in the text/.exe file

2) 新的输出将覆盖 text/.exe 文件中的现有信息

3) the delete function unable to delete correctly after the first time i delete a staff information in text file.

3) 第一次删除文本文件中的员工信息后,删除功能无法正确删除。

I would be so happy if I can solve any of these 3 problem :)

如果我能解决这三个问题中的任何一个,我会很高兴:)

The code is as follows:

代码如下:

#include <stdio.h>
#include <stdlib.h>

void Menu();
void New_Staff();
void Delete_Staff();
void Export_Profile();

struct element{
    char id[20];
    char name[20];
    char gender[20];
    char phone[20];
    char email[20];
}profile;

int main(void){      //The program will continue running until option 4 selected                                   
    int a;  

    for(a=0;;a++){
       Menu();
    }
    return 0;
}

void Menu()      //Main Menu to select option
{
    int n;
    printf("\n**********************************************");
    printf("\nMAIN MENU-STAFF INFORMATION SYSTEM");
    printf("\n**********************************************");
    printf("\n1. Add profile Staff Profile");
    printf("\n2. Delete Staff Profile");
    printf("\n3. Export All Profiles to 'output.txt'");
    printf("\n4. Exit");
    printf("\n**********************************************");
    printf("\nPlease enter your option< 1 / 2 / 3 / 4 >: ");
    scanf("%d", &n);

    switch(n){
    case 1:
        New_Staff();
        break;
    case 2:
        Delete_Staff();
        break;
    case 3:
        Export_Profile();
        break;
    case 4:
        printf("\n*** Thanks for using the program! Goodbye. ***");
        exit(0);
        break;
    default:
        printf("\nError! Wrong Number is Entered\nPlease Try Again");
        break;
    }
}

void New_Staff()                        //Add New Staff Profile 
{   
    int x;
    struct element profile;

    printf("\n===Add New Staff Profile===");
    printf("\n\nPlease enter the following staff information.");

    printf("\n\nStaff ID: ");
    scanf("%s", &profile.id);

    printf("Name\t: ");
    fflush(stdin);
    fgets(profile.name,20,stdin);

    for(x=0 ; x<20 ; x++)
    {
    if(profile.name[x] == '\n')
        profile.name[x] = '
**********************************************
MAIN MENU-STAFF INFORMATION SYSTEM
**********************************************
1. Add profile Staff Profile
2. Delete Staff Profile
3. Export All Profiles to 'output.txt'
4. Exit
**********************************************
Please enter your option< 1 / 2 / 3 / 4 >: 1

===Add New Staff Profile===

Please enter the following staff information.

Staff ID: 1
Name    : Carmen Gray
Gender  : Female
Phone   : 123-4567890
Email   : [email protected]

SYSTEM: New Staff Profile is Added Successfully.
**********************************************
MAIN MENU-STAFF INFORMATION SYSTEM
**********************************************
1. Add profile Staff Profile
2. Delete Staff Profile
3. Export All Profiles to 'output.txt'
4. Exit
**********************************************
Please enter your option< 1 / 2 / 3 / 4 >: 3

 Staff         ID       Name     Gender      Phone
   °2#                @Γg╕?         ?
SYSTEM: All staff profile have been exported to output.txt file
**********************************************
MAIN MENU-STAFF INFORMATION SYSTEM
**********************************************
1. Add profile Staff Profile
2. Delete Staff Profile
3. Export All Profiles to 'output.txt'
4. Exit
**********************************************
Please enter your option< 1 / 2 / 3 / 4 >: 2

 Staff         ID       Name     Gender      Phone
   °2#                @Γg╕?        .

Delete Staff with ID: 1

The contents of file after being modified are as follows:
 Staff         ID       Name     Gender      Phone
'; } printf("Gender\t: "); scanf("%s", &profile.gender); printf("Phone\t: "); scanf("%s", &profile.phone); printf("Email\t: "); scanf("%s", &profile.email); printf("\nSYSTEM: New Staff Profile is Added Successfully."); } void Delete_Staff() //Delete Staff Profile { FILE *fRead, *fWrite; char *TextFile; char c; int Delete_Id, temp = 1; TextFile="output.txt"; fRead = fopen(TextFile, "r"); c = getc(fRead); while (c != EOF){ printf("%c", c); c = getc(fRead); } rewind(fRead); printf("\nDelete Staff with ID: "); scanf("%d", &Delete_Id); Delete_Id=Delete_Id+1; fWrite = fopen("copy.c", "w"); c = getc(fRead); while (c != EOF) { c = getc(fRead); if (c == '\n') temp++; if (temp != Delete_Id){ putc(c, fWrite); } } fclose(fRead); fclose(fWrite); remove(TextFile); rename("copy.c", TextFile); printf("\nThe contents of file after being modified are as follows:\n"); fRead = fopen(TextFile, "r"); c = getc(fRead); while (c != EOF) { printf("%c", c); c = getc(fRead); } fclose(fRead); } void Export_Profile() //Export Staff Profile to Text { struct element profile; FILE *fPtr; fPtr=fopen("output.txt","w"); FILE *fPtr1; fPtr1=fopen("output.txt","a+"); if (fPtr == NULL) printf("Error in opening file\n"); if (fPtr1 == NULL) printf("Error in opening file\n"); fprintf(fPtr,"%10s %10s %10s %10s %10s","Staff","ID", "Name","Gender","Phone","Email"); fprintf(fPtr1,"\n%10s %10s %10s %10s %10s", profile.id, profile.name, profile.gender, profile.phone, profile.email); printf("\n%10s %10s %10s %10s %10s", "Staff", "ID", "Name", "Gender", "Phone", "Email"); printf("\n%10s %10s %10s %10s %10s", profile.id, profile.name, profile.gender, profile.phone, profile.email); printf("\nSYSTEM: All staff profile have been exported to output.txt file"); fclose(fPtr); fclose(fPtr1); }

I'm sorry for the long code. I not really sure where problem lies.

我很抱歉代码太长。我不太确定问题出在哪里。

The output give this:

输出给出了这个:

   Staff         ID       Name     Gender      Phone
     ?y#                @ag?ù         ù           

and the text file display this:

和文本文件显示:

void Export_Profile()           //Export Staff Profile to Text
{       
    struct element profile; // this has not been set to actual value.
    ...
    fprintf(fPtr1,"\n%10s %10s %10s %10s %10s", profile.id, profile.name,   
         profile.gender, profile.phone, profile.email);
    ....
}

回答by Rohan

In Export_Profile()the profilevariable is not set to appropriate value.

Export_Profile()profile变量没有被设置为适当的值。

##代码##

You may want to store data in some global variable or array of variables or linked list. Set them in New_Profile()and use them other functions like Export_Profile().

您可能希望将数据存储在某个全局变量或变量数组或链表中。设置它们New_Profile()并使用它们其他功能,例如Export_Profile().

回答by Amit Sharma

3) the delete function unable to delete correctly after the first time i delete a staff information in text file.

3) 第一次删除文本文件中的员工信息后,删除功能无法正确删除。

You are using a counter variable tempfor the id, so suppose there are 10 ids from 1-10, now you delete 6.
Next time you call Delete_Staff(), you start with temp=1. Suppose you want to delete 7, the id 7 is now on the 6th line, but you delete the 7th line.
You should rather compare the staff_idfrom the file, with the id that you want to delete.
You can use the atoifunction to convert the string to integer.

您正在temp为 id使用计数器变量,因此假设从 1 到 10 有 10 个 id,现在您删除 6。
下次您调用 时Delete_Staff(),您从 开始temp=1。假设你要删除 7,id 7 现在在第 6 行,但是你删除了第 7 行。
您应该将staff_id文件中的 id 与要删除的 id进行比较。
您可以使用该atoi函数将字符串转换为整数。

回答by Ahmed

Opening a file in "w" mode causes the deletion of its previous content. Use "a", "a+" or "r+" if you want to write without erasing previous content.

以“w”模式打开文件会导致删除其先前的内容。如果您想在不擦除以前的内容的情况下书写,请使用“a”、“a+”或“r+”。

回答by Chetan Raikwar

you should make use of "fread" and "fwrite" function for reading/writing a file. and all i/o is ideal to be done under binary mode, "rb+"/"wb+", fwrite and fread function deal with data more efficiently. I love making such menu driven programs :) . it's better to use "while(1)" indefinite loop instead of "(for(a=0;;a++)".

您应该使用“fread”和“fwrite”函数来读取/写入文件。并且所有的 i/o 都是在二进制模式下完成的,"rb+"/"wb+"、fwrite 和 fread 函数更有效地处理数据。我喜欢制作这样的菜单驱动程序:)。最好使用“while(1)”无限循环而不是“(for(a=0;;a++)”。