从文本文件读取/写入C中的链接列表

时间:2015-04-30 18:27:04

标签: c struct linked-list dynamic-memory-allocation

所以我制作了一个程序,用于获取员工的数据(身份证,姓名等)我已经获得了大部分的资料,现在我只是想知道我如何保存我在文本文件中创建的员工记录。当然,我在开始运行程序时如何打开该文本文件。

我能够正常地执行此操作,但我发现很难将其实现到教程中的代码中。

FILE *file =        fopen("C:\\Users\\Me\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");

char c;

if(file == NULL) {
    printf("Error, file not found");
}

do {
    c = fgetc(file);
    printf("%c", c);
}
while(c != EOF);

fclose(file);

这可以用于阅读(它来自我做过的另一个程序)但是现在我正在尝试添加教程所做的事情并让链接列表在退出I&时输入文本文件#39;有点无能为力。

这是教程中的代码(不是全部)

void main()
{
struct emp_data *linkList;
char name[21], desig[51], addre[25], hd[15], empEmail[15], empSal[10];
char choice;
int eno;

linkList = NULL;
printf("\n Welcome to the employee database \n");

menu();

do
{
    /*  choose oeration to be performed */
    choice = option();
    switch(choice)
    {
    case '1':
        printf("\n Enter the Employee Number      : ");
        scanf("%d", &eno);
        printf("Enter the Employee name        : ");
        fflush(stdin);
        gets(name);
        printf("Enter the Employee Department : ");
        gets(desig);
        printf("Enter the Employee Address : ");
        gets(addre);
        printf("Enter the Employee Hire Date : ");
        gets(hd);
        printf("Enter the Employee Email : ");
        gets(empEmail);
        printf("Enter the Employee Salary : ");
        gets(empSal);

        linkList = insert(linkList, eno, name, desig, addre, hd, empEmail,     empSal);
        break;
    case '2':
        printf("\n\n Enter the employee number to be deleted: ");
        scanf("%d", &eno);
        linkList = deleteNode(linkList, eno);
        break;
    case '3':
        if (linkList == NULL)
        {
            printf("\n Database empty.");
            break;
        }
        display(linkList);
        break;
    case '4':
        printf("\n\n Enter the employee number to be searched: ");
        scanf("%d", &eno);
        search(linkList, eno);
        break;
    case '5': break;
    }
} while (choice != '5');
}

我应该创建一个新方法并在main的开头调用它吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

好吧,我可能会理解这个错误,但是,如果你唯一想做的就是创建一个文本文件并将数据写入所说的文本文件,一个简单的选择就是:

fd = open(pathToYourFile, O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);

在将创建文件的窗口上,作为权限:

用户:读取+写入

allOthers:阅读。

对于Unix,您必须为组和其他人指定它们,如下所示:

fd = open(pathToYourFile, O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP);

此外,O_TRUNC只是截断文件,以便只写入您想要的信息。看看公开的人了解更多信息。

如果你想fopen更短。只是做

file = fopen(PathToYourFile, 'w+');

然后你所要做的就是写入文件。 (因此要么是fd,要么是int,要么是文件,要么是FILE *)