【发布时间】:2021-10-17 14:45:07
【问题描述】:
今天我决定人生中第一次学习编码。我决定学习 C。我创建了一个小程序来检查 txt 文件中的特定值。如果它找到该值,那么它将告诉您已找到该特定值。
我想做的是我可以把多个文件通过这个程序。我希望这个程序能够扫描文件夹中的所有文件以查找特定字符串并显示哪些文件包含该字符串(基本上是文件索引)
我今天刚开始,我 15 岁,所以我不知道我的假设是否正确,如果这听起来很愚蠢,我很抱歉,但我一直在考虑也许创建一个我放入该程序的每个目录的线程,每个线程单独在单个文件上运行该代码,然后显示可以找到该字符串的所有目录。
我一直在研究线程,但我不太了解它。这是一次一个文件的工作代码。有谁知道如何按照我的意愿进行这项工作?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//searches for this string in a txt file
char searchforthis[200];
//file name to display at output
char ch, file_name[200];
FILE *fp;
//Asks for full directory of txt file (example: C:\users\...) and reads that file.
//fp is content of file
printf("Enter name of a file you wish to check:\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
//If there's no data inside the file it displays following error message
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//asks for string (what has to be searched)
printf("Enter what you want to search: \n");
scanf("%s", searchforthis);
char* p;
// Find first occurrence of searchforthis in fp
p = strstr(searchforthis, fp);
// Prints the result
if (p) {
printf("This Value was found in following file:\n%s", file_name);
} else
printf("This Value has not been found.\n");
fclose(fp);
return 0;
}
【问题讨论】:
-
您希望同时完成还是一次只处理一个文件?
-
除此之外,去掉
gets(),它不会为溢出提供任何安全性,你应该限制scanf()读取的字符。 -
p = strstr(searchforthis, fp);不会编译。strstr在另一个字符串中搜索一个字符串。相反,您可以将文件读入缓冲区(可能一次使用fgets循环一行),然后执行p = strstr (searchforthis, buffer);。 -
另外,如果您刚刚开始,请忘记多线程。这是以后的事情,很久以后。
-
@PaulSanders 一些编译器(至少
gcc和clang)实际上接受错误的p = strstr(searchforthis, fp);并发出警告(不兼容的指针类型)。对于这些编译器,我建议添加编译器选项-Wall -Wextra -pedantic -pedantic-errors以使编译失败。添加-Werror也可能有好处。
标签: c multithreading input