简体   繁体   English

如何遍历 c 中的文件?

[英]How to iterate through files in c?

I have to write a function that given two files, compares them both and writes on a third file each word they have in common, I tried with this one, actually making it write on terminal to see if it works, it actually iterates trough the second file but it only compares the first word of the first file, any suggestions?我必须写一个 function 给定两个文件,比较它们并在第三个文件中写入它们共有的每个单词,我尝试使用这个,实际上使它在终端上写入以查看它是否有效,它实际上通过第二个文件,但它只比较第一个文件的第一个单词,有什么建议吗?

void fileCopy(FILE *f1,FILE *f2){

    char fileString1[100], fileString2[100];
    
    while(!feof(f1)){

        fscanf(f1,"%s",fileString1);

        while(!feof(f2)){

            fscanf(f2,"%s",fileString2);

            if(!strcmp(fileString1,fileString2)) printf("%s ",fileString1); 
        }
    }
}

while(!feof(f2)) loops until the end of the second file. while(!feof(f2))循环直到第二个文件结束。 You must iterate through both files simultaneously.您必须同时遍历这两个文件。 Instead of these while(.feof... you should be checking the result of each fscanf .而不是这些while(.feof...您应该检查每个fscanf的结果。

A simple pseudo code example:一个简单的伪代码示例:

while(1)
{
  int fscanf1_result = fscanf(f1, ...);
  int fscanf2_result = fscanf(f2, ...);
  if(fscanf1_result != 1 || fscanf2_result != 1)
  {
    break;
  }
  /* rest of the code here */
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM