[英]How do I read files from an string array of file names?
So im writing a program to open a directory, get all the files inside, and then read the contents of each file.所以我写了一个程序来打开一个目录,获取里面的所有文件,然后读取每个文件的内容。 currently i successfully got all the file names in a string array.目前我成功地获得了字符串数组中的所有文件名。 the print files[] loop shows all the file names, but the loop to check frequency does not read the files correctly.打印文件 [] 循环显示所有文件名,但检查频率的循环无法正确读取文件。 how do i successfully read an array of file names and then scan each of their contents?我如何成功读取文件名数组,然后扫描其中的每个内容?
//Open Directory
DIR *dr = opendir(path);
struct dirent *de;
if(dr == NULL){
printf("Could not open directory");
return 0 ;
}
const char* files[100];
int buffer=0;
//Read Directory Files
while((de = readdir(dr)) != NULL){
files[buffer] = de->d_name;
buffer++;
}
for(int x = 0; x <= buffer; x++){
printf("%s" , files[x]);
}
closedir(dr);
//Check Frequency
for(int i = 0; i <= buffer; i++){
int ch;
FILE *fp;
fp = fopen(files[i], "r");
if(fp == NULL)
continue;
ch = fgetc(fp);
while(ch != EOF){
ch = tolower(ch);
if(ch>=97 && ch<= 122){
alphabetfreq[ch-97]++;
}
ch = fgetc(fp);
}
fclose(fp);
There are multiple things wrong with the program.程序有很多问题。 But the main reason why it is not reading the files is that you are just passing the file names to fopen(), so it is looking for them in current directory and returning null values.但它不读取文件的主要原因是您只是将文件名传递给 fopen(),因此它正在当前目录中查找它们并返回空值。 Also you are not handling the null results carefully.您也没有仔细处理空结果。 And the condition in the loop should x < buffer and not x <= buffer.并且循环中的条件应该 x < buffer 而不是 x <= buffer。
#include<stdio.h>
#include<dirent.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
int main()
{
int alphabetfreq[100], i;
for(i = 0; i < 100; i++){
alphabetfreq[i] = 0;
}
char path[] = "/home/path_to_directory/";
DIR *dr = opendir(path);
struct dirent *de;
if(dr == NULL){
printf("Could not open directory");
return 0 ;
}
const char* files[100];
int buffer=0;
//Read Directory Files
while((de = readdir(dr)) != NULL){
files[buffer] = de->d_name;
buffer++;
}
for(int x = 0; x < buffer; x++){
printf("%s" , files[x]);
}
closedir(dr);
printf("\n");
//Check Frequency
for(int i = 0; i < buffer; i++){
int ch;
FILE *fp;
char * file = malloc(strlen(path) + strlen(files[i]) + 1);
strcpy(file, path);
strcat(file, files[i]);
fp = fopen(file, "r");
if(fp == NULL)
{
printf("no file %s\n", file);
continue;
}
ch = fgetc(fp);
while(ch != EOF){
ch = tolower(ch);
if(ch>=97 && ch<= 122){
alphabetfreq[ch-97]++;
}
ch = fgetc(fp);
}
fclose(fp);
}
for(i = 0; i < 26; i++)
{
printf("%c %d\n", i+97, alphabetfreq[i]);
}
}
This is working for me.这对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.