我试图计算一个单词在各种文本文件中出现的次数,但无法打开这些文件。我有一个带有此文件路径的目录:“ C:\ Users \ matti \ example”,示例目录中有2个包含一些单词的文本文件。
我试图将目录更改为另一个文件路径,但结果相同。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#define BUFFERSIZE 1000
/* Function declarations */
int countOccurrences(FILE *fptr, const char *word);
int main(int argc, char **argv)
{
int wCount;
DIR *FD;
struct dirent* in_file;
FILE *entry_file;
char dirPath[100];
char word[50];
/* Input word to search in file */
printf("Enter word to search in file: ");
scanf("%s", word);
/* Input directory path */
printf("Enter dir path: ");
scanf("%s", dirPath);
/* Scanning the in directory */
FD = opendir (dirPath);
if (FD == NULL)
{
fprintf(stderr, "Error: Failed to open input directory - %s\n", strerror(errno));
return 1;
}
while ((in_file = readdir(FD)))
{
/* On Linux/Unix we don't want current and parent directories
* On Windows machines too, thanks Greg Hewgill
*/
//printf("%s\n", in_file->d_name);
if (!strcmp (in_file->d_name, "."))
continue;
if (!strcmp (in_file->d_name, ".."))
continue;
/* Open directory entry file for common operation */
entry_file = fopen(in_file->d_name ,"r");
if (entry_file==NULL)
{
fprintf(stderr, "Error : Failed to open entry file - %s\n", strerror(errno));
return 1;
}
//search occurrences of word
wCount = countOccurrences(entry_file, word);
printf("'%s' is found %d times in file.", word, wCount);
wCount=0;
fclose(entry_file);
}
return 0;
}
int countOccurrences(FILE *fptr, const char *word)
{
char str[BUFFERSIZE];
char *pos;
int index, count;
count = 0;
// Read line from file till end of file.
while(fgets(str,BUFFERSIZE,fptr)!=NULL)
{
index = 0;
// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
// Index of word in str is
// Memory address of pos - memory
// address of str.
index = (pos - str) + 1;
count++;
}
}
return count;
}
在Windows 10中的命令提示符中执行代码的结果是:
Enter word to search in file: ciao
Enter dir path: C:\Users\matti\example
Error : Failed to open entry file - No such file or directory
请问有人可以帮我吗?
已解决! 我必须将目录路径与fopen函数的文件名连接起来。
/* Concatenate string to make the completePath for function fopen*/
char completePath [50];
strcat(completePath,dirPath);
strcat(completePath,"\\");
strcat(completePath,in_file->d_name);
/* Open directory entry file for common operation */
entry_file = fopen(completePath, "r");