【问题标题】:Reading/Writing from a text file to a linked list in C从文本文件读/写到C中的链表
【发布时间】:2015-07-10 14:09:06
【问题描述】:

所以我正在制作一个接收员工数据(id、姓名等)的程序。我已经从 sanfoundry 教程中获得了大部分内容,现在我只是想知道如何保存员工记录我在一个文本文件中创建。当然还有在开始运行程序时如何打开该文本文件。

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

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);

这适用于读入(它来自我所做的另一个程序)但是现在我正在尝试添加教程的功能并让链表在退出时写入文本文件,我有点无能为力。

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

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 的开头调用它吗?任何帮助将不胜感激。

【问题讨论】:

  • fgetc 返回int(不是char
  • 好的...关于如何解决我的问题有什么想法吗?
  • int fgetc( std::FILE* stream ) .. [链接]更多信息en.cppreference.com/w/cpp/io/c/fgetc
  • 您的问题是读数不正确?或者你得到一个特定的异常/错误?

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


【解决方案1】:

好的,我可能理解错了,但是,如果您只想创建一个文本文件并将数据写入所述文本文件,那么一个简单的选择就是:

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

在将创建具有权限的文件的窗口上:

用户:读+写

所有其他:阅读。

对于 Unix,您必须为组和其他指定,所以它看起来像:

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

另外,O_TRUNC 只是截断文件以便只在其中写入您想要的信息。环顾 open man 以了解更多信息。

如果你想让 fopen 更短。做吧

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

然后您所要做的就是写入文件。 (所以要么是 fd,一个 int,要么是文件,一个 FILE *)

【讨论】:

    猜你喜欢
    • 2013-07-19
    • 2018-06-02
    • 2019-10-17
    • 2017-05-03
    • 2023-03-17
    • 2019-11-07
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多