[英]Why wont the program read from the 2 argument file?
因此,该任务是使用要搜索的输入文件和要搜索的输入来实现子字符串搜索程序。 我创建了以下代码:
#include <stdio.h>
#include <string.h>
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 <stdio.h>
#include <string.h>
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;
}
主要区别在于这循环从输入文件读取多行。 您的文件只能用于单行输入的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.