unix下文件移动的问题

xwchena 2002-09-16 11:45:11
代码如下:

if( (stream = fopen(sSourceFile,"r")) == NULL) //判断文件是否存在
{
return NOTFINDFILE;
}
else //文件存在,把文件移到别的地方
{
fclose(stream);
sprintf(sCommand,"mv %s %s",sSourceFile,sDesFile);
if( popen(sCommand,"r")==NULL )
printf("移动失败");
else
printf("移动成功");
}
执行后可以生成sDesFile,但是字节数为0,而且sSourceFile还存在,这是什么原因?
...全文
102 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
Last_Dodo 2002-09-17
  • 打赏
  • 举报
回复
Why popen? You better read the mannual page (man popen).

Here couple of examples (there are many ways to do it):

1. for performance:
if (access(sSourceFile, F_OK) < 0) { //no such a file
return FILENOTFOUND;
}

if (link(sSourceFile, sDesFile) < 0){
//handle errno here to better indicate what the problem is
printf("Can not move to new file\n");
return CANNOTCREATENEWFILE;
}

if (unlink(sSourceFile) < )){
//handle errno here
return CANOTMOVE;
}

2. For simpler code:

sprintf(sCommand, "mv %s %s", sSourceFile, sDesFile);
if (system(sCommand) < 0){
return CANNOTMOVE;
}
pi1ot 2002-09-17
  • 打赏
  • 举报
回复
if ( access(filename,F_OK) == 0 )
return true;
else
return false;
xwchena 2002-09-17
  • 打赏
  • 举报
回复
各位有没有发现用
access(sSourceFile, F_OK) < 0) { //no such a file
return FILENOTFOUND;
}
会误报的问题?就是文件存在,返回值也是<0的?
darkelf 2002-09-17
  • 打赏
  • 举报
回复
我遇到过这样的问题,你最好用system来执行你的shell命令吧
返回值为0表示正确,否则不正确

good luck!
pi1ot 2002-09-17
  • 打赏
  • 举报
回复
改名直接 rename(),ANSI C 函数.
xwchena 2002-09-17
  • 打赏
  • 举报
回复
应该不存在“不在同一个卷”的问题,因为我是在同一个目录下,我用
mv 就是想实现文件改名
xwchena 2002-09-17
  • 打赏
  • 举报
回复
这种情况也不是一直这样,程序运行一段时间后就会出现这种情况,重起后又能正常运行一段时间

程序执行一段时间后,stream = fopen(sSourceFile,"r");有时候文件即使存在,返回的值也是NULL,重起后又会正常一阵子,总是时好时坏
Last_Dodo 2002-09-17
  • 打赏
  • 举报
回复
pi1ot pointed out a good point, but should be "file system" instead of "volume".
blh 2002-09-17
  • 打赏
  • 举报
回复
我在linux没问题,呵呵
看看你有没有对文件的读写权限
pi1ot 2002-09-17
  • 打赏
  • 举报
回复
mv的源码是先 link(),unlink,不行(就是说不在同一个卷)再 copy, delete.
xwchena 2002-09-17
  • 打赏
  • 举报
回复
看来只好先改用access和rename了,希望产品上线后不再出类似的问题
各位如果还有好的建议,希望能帮一把,谢谢

70,020

社区成员

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

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