我正在尝试读取名为“数据集”的目录中的所有.txt文件。所有文本文件的名称都类似于1.txt,2.txt,3.txt ...,然后将文件内容保存到名为FILES的结构中。
在某些资料中,我使用了dirent.h库和readdir()函数。但是程序从目录读取的文件名未正确返回。这是我的相关代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
typedef struct FILES{
char **words;
int wordCount;
}FILES;
void readFiles();
FILES *files;
int fileCount;
int main(){
readFiles();
return 0;
}
void readFiles(){
FILE *file;
DIR *directory;
struct dirent *filesInDirectory;
int counter;
fileCount = 1;
files = (FILES *)malloc(sizeof(FILES));
directory = opendir("dataset");
if(directory == NULL){
printf("Warning: The directory name that is given in the code is not
valid ..!");
return;
}else{
while((filesInDirectory = readdir(directory)) != NULL){
printf("%s\n", filesInDirectory->d_name);
file = fopen(filesInDirectory->d_name, "r+");
if(file == NULL){
printf("Warning: The file named %s could not open ..!",
filesInDirectory->d_name);
return;
}
files[fileCount-1].wordCount = 1;
files[fileCount-1].words = (char **)malloc(files[fileCount-
1].wordCount * sizeof(char *));
counter = 0;
while(!feof(file)){
files[fileCount-1].words[counter] = (char *)malloc(20 *
sizeof(char));
fscanf(file, "%s", files[fileCount-1].words[counter]);
files[fileCount-1].wordCount++;
files[fileCount-1].words = (char **)realloc(files[fileCount-
1].words, files[fileCount-1].wordCount * sizeof(char *));
counter++;
}
fileCount++;
fclose(file);
}
}
}
我在此处打印的文件名“ printf(“%s \ n”,filesInDirectory-> d_name);” 是“。”。我在哪里做错了?
这不是评论的太大答案
这是您的问题:
1。
files = (FILES *)malloc(sizeof(FILES));
这个足够一个FILES
。这还不够
后
while((filesInDirectory = readdir(directory)) != NULL){
把像
size_t len = strlen(filesInDirectory->d_name);
if (len < 5 || strcmp(filesInDirectory->d_name + len - 4, ".txt") != 0) {
continue;
}
这将检查以确保文件以.txt结尾
考虑使用fstat
以确保该文件是文本文件
删除对malloc的转换
也许realloc
用于files
while ... feof
不好-请参见上面的链接
fscanf(file, "%s",
-缓冲区超限是可能的。为此做些事情。阅读手册页
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句