#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
struct string_count_struct{
char fname;
char str;
long long count;
};
void* filesearch(void* arg)
{
//get the file name
struct string_count_struct *arg_ptr = (struct string_count_struct*) arg;
int line_num = 1;
int find_result = 0;
char temp[512];
//create a file pointer
FILE *fp;
fp = fopen(arg_ptr -> fname, "r");
//dont forget error handling
if (fp == NULL){
printf("File could not be opened");
return(-1);
}
while (fgets(temp, 512, fp) != NULL) {
if ((strstr(temp, arg_ptr -> str)) != NULL) {
find_result++;
}
line_num++;
}
if(find_result = 0) {
printf("\nSorry, couldn't find a match.\n");
}
arg_ptr -> count = find_result;
//close the file
if (fp){
fclose(fp);
}
pthread_exit(0);
}
int main (int argc, char **argv)
{
if (argc < 3) {
printf("Usage: <file> <string> <arg1> <arg2>...<argN>\n", argv[0]);
exit(-1);
}
int num_args = argc - 2;
struct string_count_struct args[num_args];
//Thread Creation:
pthread_t tids[num_args];
for(int i = 0; i < num_args; i++) {
args[i].fname = atoll(argv[i + 2]);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tids[i], &attr, filesearch, &args[i]);
}
//Wait until work is completed
for (int i = 0; i < num_args; i ++){
pthread_join(tids[i], NULL);
printf("blah is blah %lld\n", args[i].count);
}
return 0;
}
以下是我的警告
root@kali:~/Desktop# gcc prog2.c -lbthread
prog2.c: In function ‘filesearch’:
prog2.c:29:13: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [-Wint-conversion]
fp = fopen(arg_ptr -> fname, "r");
^~~~~~~
In file included from prog2.c:1:0:
/usr/include/stdio.h:274:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
extern FILE *fopen (const char *__restrict __filename,
^~~~~
prog2.c:34:8: warning: return makes pointer from integer without a cast [-Wint-conversion]
return(-1);
^
prog2.c:38:21: warning: passing argument 2 of ‘strstr’ makes pointer from integer without a cast [-Wint-conversion]
if ((strstr(temp, arg_ptr -> str)) != NULL) {
^~~~~~~
In file included from prog2.c:4:0:
/usr/include/string.h:337:14: note: expected ‘const char *’ but argument is of type ‘char’
extern char *strstr (const char *__haystack, const char *__needle)
^~~~~~
prog2.c: In function ‘main’:
prog2.c:78:17: error: assignment of read-only member ‘fname’
args[i].fname = atoll(argv[i + 2]);
我不确定我做错了什么,这些错误阻止我的程序正确读取所需文件并计算用户将选择的特定字符串的出现次数。 我已修复错误但未修复警告。
程序将采用命令行参数,为每个要搜索的文件创建单独的线程,搜索每个文件,然后给出结果。我计划使用Mutex进行进一步改进,但是现在我只是想解决我的I / O问题。
答案 0 :(得分:0)
只是解决了一些警告,我不确定这是否会使代码有效:
在第29行中,fopen需要一个文件名(char *
),但fname只是string_count_struct中的char
。设为char*
。在main函数中,您将其中一个参数从ASCII转换为long long
并将其分配给fname,后者稍后将用作fopen()
的文件名。这可能不是你想要做的。
在第34行中,返回-1,这不是指针。您声明该函数返回一个void指针。让它返回(0)(或返回(NULL))。
与第29行中的第29行相同:struct string_count_struct中的str
只是char
,但strstr需要char*
。也可以char*
。
您的“用法”缺少“%s”格式字符串,以实际打印参数argv [0]。