c - 在 C 中从文本文件读/写到链表

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

所以我正在制作一个程序,该程序接收员工的数据(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);

这适用于读入(它来 self 所做的另一个程序),但现在我试图添加教程的内容,并在退出时将链接列表写入文本文件,我有点无能为力。

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

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

最佳答案

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

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

在 Windows 上,将创建一个具有如下权限的文件:

用户:读+写

所有其他:阅读。

对于 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,一个 FILE *)

关于c - 在 C 中从文本文件读/写到链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29975086/

相关文章:

c++ - C++中的反向遍历单链表

java - 尝试将 ArrayList 转换为 LinkedList。不知道为什么这不起作用

c++ - 添加带链表的中间节点

c - C 中使用三元运算符进行版本字符串比较

c - 在C中将指针传递给结构数组

C Fread 将文本文件拆分为 block

c - 如何使用默认值初始化 C 结构体

C:如何使 ArrayList 实现与 UNICODE_STRING 数据兼容?

c - 从C中的十六进制地址中提取MSB和LSB

c - 如何将字符串转换为整数