我用的工具是dev-c++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int main( void )
{
FILE *fp;
int static i=0;
char const path2[]="C:\\Documents and Settings\\Administrator\\桌面\\test";
DIR *directory_pointer;
struct dirent *entry;
if ( ( directory_pointer=opendir( path2 ) ) == NULL )
{
printf( "Error opening \n ");
system( "pause" );
return -1;
}
char *path;//定义一个指针
path=(char *)realloc(NULL, strlen(path2)+1 );//分配其空间
strcpy(path, path2);//复制路径
strcat(path,"\\");//补充\\为完整的路径
printf( "你的文件夹路径为%s\n\n" ,path);
while( ( entry=readdir(directory_pointer)) != NULL )
{
//memset(path,0,sizeof(path));
path=(char *)realloc(path, ( strlen(path) + strlen(entry->d_name) + 1 ) );//重新计算其空间 ,可以改变其内存空间的大小
strcat(path,entry->d_name);
//printf( "完整文件名为%s\t" ,path);
if ( (fp = fopen( path,"r" )) == NULL )
{
fprintf(stderr,"无法打开%s文件\n",entry->d_name);
continue;
}
fclose(fp);
printf( "完整文件名为%s\t" ,path);
printf( "第%d个\n" ,i);
i++;
//memset(path,0,strlen(entry->d_name));
}
//free(path)
closedir(directory_pointer);
printf( "The current path : %s\n ", getenv( "USER" ) );
system( "pause" );
return 0;
}
问题可能是出在fopen的路径上, //printf( "完整文件名为%s\t" ,path);取消注释可以发现
每次申请的内存保存了上次的文件名,
但是我不知道怎么写才能正确
------解决方案--------------------
.是本级目录
..是上级目录
在循环中判断过滤
------解决方案--------------------
realloc
Reallocate memory blocks.
void *realloc( void *memblock, size_t size );
Routine Required Header Compatibility
realloc <stdlib.h> and <malloc.h> ANSI, Win 95, Win NT
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version
Return Value
realloc returns a void pointer to the reallocated (and possibly moved) memory block. The return value is NULL if the size is zero and the buffer argument is not NULL, or if there is not enough available memory to expand the block to the given size. In the first case, the original block is freed. In the second, the original block is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value.
Parameters
memblock
Pointer to previously allocated memory block
size
New size in bytes
Remarks
The realloc function changes the size of an allocated memory block. The memblock argument points to the beginning of the memory block. If memblock is NULL, realloc behaves the same way as malloc and allocates a new block of size bytes. If memblock is not NULL, it should be a pointer returned by a previous call to calloc, malloc, or realloc.