为什么程序不会从2参数文件读取?

因此,分配是使用要搜索的输入文件和要搜索的输入来实现子字符串搜索程序。 我创建了以下代码:

#include  #include  int main(int argc,char *argv[]) { FILE *fp; fp = fopen(argv[1],"r"); if (fp == NULL) { printf("Error"); return 0; } char* tmpp[100]; int count = 0; char* nexts = argv[2]; char* tmp = fgets(tmpp,100,fp); while(tmp = strstr(tmp,nexts)) { count++; tmp++; } printf("%d\n\n",count); fclose(fp); return 0; } 

程序编译但是当我在ubuntu终端中实现它时:

 echo "aabb" >beta ./a.out beta a 1 

为什么程序不使用第一个参数(argv [1])作为beta而第二个参数(argv [2])作为正确的?

您应该打开一个文件,然后从该文件中读取字节到临时缓冲区:

 FILE *file = fopen("file", "r"); while (1) { char buffer[BUFSIZ+1]; size_t nread = fread(buffer, 1, sizeof(buffer)-1, file); if (nread == 0) break; // read error or EOF buffer[nread] = 0; // chunk with BUFSIZ amount of bytes is available via buffer (and is zero-terminated) } 

如果要在文件中搜索字符串/模式,请注意文件中的外观模式可能会跨越您的块大小边界,例如:您查找“hello”,BUFSIZ为512.文件在字节处包含“hello” 510.显然,如果你读到512,你将获得以“he”结尾的第一个块,以及以“llo”开头的第二个块。 这种情况的概率对于所有块大小都是非零的(SIZE_MAX除外,但由于其他原因, 缓冲区大小是不可能的)。 处理边界可能非常复杂。

关闭……但这更接近:

 #include  #include  int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s file pattern\n", argv[0]); return 1; } FILE *fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(stderr, "Error: failed to open file %s for reading\n", argv[1]); return 1; } char tmpp[1000]; int count = 0; char* nexts = argv[2]; while (fgets(tmpp, sizeof(tmpp), fp) != 0) { char *tmp = tmpp; while ((tmp = strstr(tmp, nexts)) != 0) { count++; tmp++; } } printf("%d\n", count); fclose(fp); return 0; } 

主要区别在于此循环从输入文件中读取多行。 你的工作只能处理单行输入的文件。