【问题标题】:Search text file for string and copy it's line to another file在文本文件中搜索字符串并将其复制到另一个文件
【发布时间】:2016-08-02 00:53:27
【问题描述】:

我有一个充满姓氏的数组。我希望我的程序按如下方式使用这些姓氏:

  • 搜索两个文件,如果在给定点找到姓氏,则复制该行的其他详细信息,并将它们打印到排序文件中。

姓氏按字母顺序排列。我正在使用 fscanf 读取信息,然后使用 strcmp 查看字符串是否相同,但是当我运行程序时,它只是将一个学生的名字复制到文件中,没有别的。这是我正在使用的代码:

for(i=0; i<SURNAMES; i++)
{
    //Search file 1
    while (fscanf(fp, "%d %s %s %s",&student_id,first_name,surname,student_type) != EOF)
    {
            if(strcmp(surnames[i], surname) == 0)
            {
                fprintf(sorted_students, "%d %s %s %s\n",student_id,first_name,surname,student_type);
            }
    }

    //Search file 2
    while (fscanf(fp2, "%d %s %s %s",&student_id,first_name,surname,student_type) != EOF)
    {
            if(strcmp(surnames[i], surname) == 0)
            {
                fprintf(sorted_students, "%d %s %s %s\n",student_id,first_name,surname,student_type);
            }
    }

}

当我将 for 循环放在 while 循环中时,它以某种方式起作用,但是当我这样做时,最初可能在第二个文件中的学生将被忽略。如果我将 for 循环放入其中,那么按字母顺序对学生进行排序的整个想法就会丢失,并且不会根据他们在原始数组中的位置进行排序。

【问题讨论】:

    标签: c file sorting


    【解决方案1】:

    你应该从文件的第一个开始,每次都在“for循环”的第一个! 使用 fseek 函数。

    fseek(fp, 0, SEEK_SET);
    fseek(fp2, 0, SEEK_SET);
    

    【讨论】:

    • 我不太确定你的意思。
    • 是的,因为每次你到文件的末尾来完全搜索它们。所以,你应该每次都第一时间去。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2013-06-25
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    相关资源
    最近更新 更多