如何在while循环C中连接两个字符串

如何在while循环C中连接两个字符串,c,fgets,C,Fgets,我正在使用两个txt文件(“names.txt”、“fixes.txt”),需要逐行读取这些文件的单词,并将它们连接到一个新文件(“results.txt”)。 例如,名称文件包含以下内容: john william brad @123 @321 @qwe 修复文件包含以下内容: john william brad @123 @321 @qwe 代码如下: #include <stdio.h> #include <stdlib.h> #include <st

我正在使用两个txt文件(“names.txt”、“fixes.txt”),需要逐行读取这些文件的单词,并将它们连接到一个新文件(“results.txt”)。 例如,名称文件包含以下内容:

john
william
brad
@123
@321
@qwe
修复文件包含以下内容:

john
william
brad
@123
@321
@qwe
代码如下:

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

int main(int argc, char *argv[])
{
    char * filename = argv[1];
    char * fixname = argv[2];
    char names[100];
    char fixes[100];
    FILE * fptr = fopen(filename, "r");
    FILE * fpt = fopen(fixname, "r");
    FILE * fp = fopen("results.txt", "w");
    while (fgets ( names, sizeof(names), fptr ) != NULL)
    {
        strtok(names, "\n");
        while(fgets ( fixes, sizeof(fixes), fpt ) != NULL)
        {
            fprintf(fp, "%s%s", names, fixes);
        }
    }

    return 0;
}
但是,结果是:

john@123
john@321
john@qwe

它不会得到其他的名字

在外部while循环的第一次迭代中,内部while循环生成输入文件的EOF条件
fixname

因此,外部while循环的其他迭代会跳过内部while循环的计算,因为这种情况

while(fgets ( fixes, sizeof(fixes), fpt ) != NULL)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
等于假


例如,使用一个外部while循环,并在其中使用if语句而不是内部while循环。

正如Vlad所指出的,内部循环指向外部循环第一次迭代后的EOF。 因此,外部循环的后续迭代将跳过内部循环

要解决这个问题,可以在每次迭代后将指针“fpt”返回到文件的开头

while (fgets ( names, sizeof(names), fptr ) != NULL)
{
    strtok(names, "\n");
    while(fgets ( fixes, sizeof(fixes), fpt ) != NULL)
    {
        fprintf(fp,"%s%s", names, fixes);
    }
    fseek(fpt,0,SEEK_SET);//bring fpt back to the beginning of the stream
}