我现在已经面对这个问题大约两个星期了,通过我已经做过的所有搜索(我已经非常了解你)我还没有找到解决方案。这是我的功能:
void delete( int sock, char *fileName ) {
unsigned int tid = (unsigned int)pthread_self();
if ( fileExists( fileName ) != 0 ) {
char msg[20];
strcpy( msg, "ERROR NO SUCH FILE\n" );
send( sock, msg, strlen( msg ), 0 );
printf( "[thread %u] Sent: %s", tid, msg );
}
if ( remove( fileName) != 0 ) {
send( sock, FAILURE, strlen( FAILURE ), 0 );
printf( "[thread %u] Sent: %s", tid, FAILURE );
} else {
send( sock, SUCCESS, strlen( SUCCESS ), 0 );
printf( "[thread %u] Sent: %s", tid, SUCCESS );
}
}
此函数用于我在C中编写的FTP服务器的一部分,其中客户端可以输入的一个命令是从服务器存储中删除特定文件(这是一个标记为"的文件夹。存储/"在我的硬盘上)。 fileExists()函数的代码如下:
int fileExists( char *fileName ) {
struct stat buf;
return ( stat( fileName, &buf ) == 0 );
}
当我运行我的代码并告诉服务器删除一个文件(我知道存在的事实)时,remove()
函数返回错误"没有这样的文件或目录" (在我的代码的旧版本中,我使用perror()
来确定错误是什么)。但是,fileExists()
函数返回0,表示文件确实存在。
有没有人遇到stat()
报告文件存在但remove()
没有问题的问题?我真的把头发拉出来试图弄清楚这个,我还没有找到解决方法。非常感谢任何帮助。
remove()
似乎并不喜欢我发送它的字符串上的空终结符。但是,我确实同意我的fileExists()
功能有点误导。我会改变它以使其更容易(如果只是为了我自己)。
答案 0 :(得分:1)
stat()
将返回-1
。在这种情况下,stat(fileName, &buf) == 0
为0
。因此,您应该替换
if ( fileExists( fileName ) != 0 ) {
与
if ( fileExists( fileName ) == 0 ) {
检查错误情况。
如果您“知道该文件存在的事实”,那么问题可能是fileName
是一个相对路径,相对于当前工作目录解析
这个过程。
请注意,您实际上根本不需要单独的fileExists()
功能(和
如果在fileExists()
之间删除文件,则存在小的竞争条件
和remove()
电话)。最好只是尝试删除该文件,然后选中errno
如果失败了:
void delete( int sock, char *fileName ) {
unsigned int tid = (unsigned int)pthread_self();
if ( remove( fileName) != 0 ) {
if (errno == ENOENT) {
// file does not exist
char msg[20];
strcpy( msg, "ERROR NO SUCH FILE\n" );
send( sock, msg, strlen( msg ), 0 );
printf( "[thread %u] Sent: %s", tid, msg );
} else {
// some other error ...
send( sock, FAILURE, strlen( FAILURE ), 0 );
printf( "[thread %u] Sent: %s", tid, FAILURE );
}
} else {
send( sock, SUCCESS, strlen( SUCCESS ), 0 );
printf( "[thread %u] Sent: %s", tid, SUCCESS );
}
}
答案 1 :(得分:1)
以下是stat
..
成功时,返回零。出错时,返回-1,并正确设置errno。
您正在检查您的函数是否返回零..
int fileExists( char *fileName ) {
struct stat buf;
return ( stat( fileName, &buf ) == 0 );
}
假设文件存在..那么返回条件将返回true
(非NULL值),因为stat
将返回0
并且满足条件。
但这种检查显然是正确的。
if(fileExists(fileName)!= 0){
并且你的男女同校打印'错误文件不存在'..
将您的条件更改为
if(fileExists(fileName)== 0){
答案 2 :(得分:1)
当我将remove()
与变量(例如char* fileName
)一起使用时,它失败了,将错误报告为No such file or directory
。但是,当我使用字符串文字(也就像remove( "abc.txt" );
)运行函数时,它会成功。经过大量测试后,remove()
似乎不是null终结符的粉丝。我目前认为这是我问题的根源。