关于指针与字符串保存文件

dayong98 2011-06-27 12:28:39
目的:取得目录下所有文件名,保存成txt文件。
问题:使用字符指针数组成功取得文件名,保存指针数组时不能成功保存已经取得的文件名。
自己不知道问题出在那里,希望大家来帮我解答一下,希望能具体些(因为本人是超级初学者),谢谢。
使用编译器:DEV-C++ 4992
代码如下:

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

int GetFileName(char *Directory);
int SaveFileName(int Num);
char *ch[100];

int main(int argc,char *argv[])
{
SaveFileName(GetFileName(argv[1]));
return 0;
}

int GetFileName(char *Directory)
{
DIR *d;
struct dirent *dr;
struct stat sbuf;
int i=0;
if((d=opendir(Directory)) == NULL)
return;
chdir(Directory);
while((dr=readdir(d)) != NULL)
{
stat(dr->d_name,&sbuf);
if(S_ISDIR(sbuf.st_mode))
continue;
else
ch[i++]=dr->d_name;
}
closedir(d);
return i;
}

int SaveFileName(int Num)
{
FILE *fp;
int i;
fp=fopen("test.txt","w");
for(i=0;i<=Num;i++)
{
fprintf(fp,"%s\n",ch[i]);
printf("%d : %s\n",i,ch[i]);
}
fclose(fp);
return 0;
}

...全文
123 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
bdmh 2011-06-27
  • 打赏
  • 举报
回复
怎么不能保持,自己调试吧,断点在fprintf,根据具体现象调试吧
dayong98 2011-06-27
  • 打赏
  • 举报
回复
感谢大家的回答,特别感谢lucifer。改正后如下:
1 char str[100][30]; 使用字符数组str来代替指针ch
2 ch[i++]=dr->d_name; 改为
strcpy(str[i++],dr->d_name);

顺便再问一个问题,希望大家指教

生成r.exe文件后在文件所在目录下(c:\dev-cpp\code)在cmd窗口下运行 r c:\windows
test.txt文件为什么不是出现在c:\dev-cpp\code目录下,而是出现在c:\windows目录下?如果要想要
test.txt出现在c:\dev-cpp\code目录下需要怎么办?
zero_to 2011-06-27
  • 打赏
  • 举报
回复
指针数组只是存的一个地址,并不能保证那块内存存的东西不变~
luciferisnotsatan 2011-06-27
  • 打赏
  • 举报
回复
给每个指针malloc空间,然后memcpy或strcpy。
dayong98 2011-06-27
  • 打赏
  • 举报
回复
如何才可以把指针指向的内容存起来呢?好像用SaveFileName()函数调用ch[]的时候,ch[]指向的就是最后取得的那个文件名?
还希望能讲的再详细些,谢谢。
luciferisnotsatan 2011-06-27
  • 打赏
  • 举报
回复
ch[i++]=dr->d_name; 只是把指针指向name,while不停循环,dr->d_name的值不停在变

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧