所以我试图创建一个接收输入目录的函数,只检查它的“.txt”文件,然后将所有内容存储到一个字符数组中(这里是动态分配的)。当我对每个文件中的每个字符使用 getc() 时,一次一个,我不仅一次存储每个字符,而且我希望它们一次打印一个字符,以查看是否所有文件正在正确读取。请注意,这里的 else 循环中的所有内容在我制作的另一个程序中仅读取单个输入文件时 100% 正确工作。
这是alphabetcount.c,它只是函数......
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include<unistd.h>
#include <stdbool.h>
#include <dirent.h>
#include "count.h"
void alphabetlettercount( char *path, char *filetowrite, long alphabetfreq[] )
{
DIR *dir;
FILE *entry_file;
struct dirent *in_file;
int c, i;
int filled_elements = 0;
char *temp_arrayPointer;
char *perm_arrayPointer;
perm_arrayPointer = ( char* ) calloc ( 1, sizeof( char ) );
dir = opendir( path );
if( dir == NULL )
{
printf( "Unable to read directory!" );
exit( 1 );
}
while( ( in_file = readdir( dir ) ) != NULL )
{
if ( !strcmp ( in_file->d_name, "." ) || !strcmp ( in_file->d_name, ".." ) || strstr( ( in_file->d_name ), ".txt" ) )
{
}
else
{
printf( "%s\n", in_file->d_name );
entry_file = fopen( in_file->d_name, "r" );
if ( entry_file != NULL )
{
while ( ( c = getc( entry_file ) ) != EOF )
{
*( perm_arrayPointer + filled_elements ) = c;
printf( "%c", ( *( perm_arrayPointer + filled_elements ) ) );
filled_elements++;
temp_arrayPointer = ( char* ) realloc ( perm_arrayPointer, ( ( filled_elements + 1 ) * sizeof( char ) ) );
if ( temp_arrayPointer != NULL )
{
perm_arrayPointer = temp_arrayPointer;
}
}
}
fclose( entry_file );
}
closedir( dir );
}
这是 testingalphabetcount.c,或者只是 main()...
(注意:alphabetlettercount() 原型存在于两个 .c 文件的 count.h #include 文件中)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include<unistd.h>
#include <stdbool.h>
#include <dirent.h>
#include "count.h"
int main()
{
char *path = "../data"; // the data *.txt files are under this folder
alphabetlettercount(path); // process the data files
}
对此的输出是...
.
.
..
..
...如果“ printf("%s\n", in_file->d_name ); ”被放置在“If”循环内,但如果它被放置在“else”循环内,我的输出是......
test2.txt
Segmentation Fault
关于我做错了什么的任何建议?我认为这与 fopen() 使用不正确有关吗?感谢和抱歉长时间阅读!