[英]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.