![](/img/trans.png)
[英]I read a string from a file and store it into an array, but how do I know the length of the array?
[英]How do I read files from an string array of file names?
所以我寫了一個程序來打開一個目錄,獲取里面的所有文件,然后讀取每個文件的內容。 目前我成功地獲得了字符串數組中的所有文件名。 打印文件 [] 循環顯示所有文件名,但檢查頻率的循環無法正確讀取文件。 我如何成功讀取文件名數組,然后掃描其中的每個內容?
//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);
程序有很多問題。 但它不讀取文件的主要原因是您只是將文件名傳遞給 fopen(),因此它正在當前目錄中查找它們並返回空值。 您也沒有仔細處理空結果。 並且循環中的條件應該 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]);
}
}
這對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.