使用c中的循环打开多个文件

问题描述

我有三个文件file1.txtfile2.txtfile3.txt,我想循环打开它们,以便可以通过循环对每个文件执行操作。我使用数组吗?我怎样才能做到这一点?目前我的代码只打开一个文件,看起来像这样:

char filename[] = "file1.txt",record[100];
FILE *fPtr;
fPtr = fopen(filename,"r");

     while (fgets(record,100,fPtr))
     {
      //code where i look for certain strings in the file
     }
fclose (fPtr);

是否可以使fPtr依次打开这3个文件,以便可以循环访问所有3个文件以执行某些操作?如果有人可以解释如何将不胜感激。

解决方法

我认为您应该可以通过循环遍历它们来解决问题。假设您有以下三个文件:

src : $ cat file1.txt 
StackOverflow is cool
src : $ cat file2.txt 
I use StackOverflow daily
src : $ cat file3.txt 
I use Github daily
src : $ cat file4.txt
I use StackO
verflow on weekends 

您可以将文件名放在这样的数组中:

char fileNames[3][10] = { "file1.txt","file2.txt","file3.txt","file4.txt"};

我从评论中注意到,您想在这些文件中搜索一些字符串。例如,如果我想在这些文件中搜索字符串“ StackOverflow”,我可以简单地对其进行迭代,并调用一个搜索方法,该方法将在提供指向文件的指针和要搜索的字符串时搜索提供的字符串。这是它的外观:

char searchStr[] = "StackOverflow";

for (int i = 0; i < 4; i++) {
  FILE *pFile = fopen(fileNames[i],"r");
  bool bExists = searchInFile(pFile,searchStr);
  if (bExists) {
    printf("%s contains %s\n",fileNames[i],searchStr);
  }
  fclose(pFile);
}

您可以使用searchInFile方法提取用于搜索文件的常见逻辑:

bool searchInFile(FILE *pFile,char *str) {
  char buffer[1024]; // buffer to read whole file in memory
  char temp[100]; // temporary buffer to read line

  buffer[0] = '\0'; // Initialize empty string
  while (fgets(temp,100,pFile) != NULL) {
      temp[strlen(temp) - 1] = '\0';
      strcat(buffer,temp); // Concatenate lines into single string
  }

  return strstr(buffer,str) != NULL; // Search for target string
}

运行以上代码时的输出:

file1.txt contains StackOverflow
file2.txt contains StackOverflow
file4.txt contains StackOverflow