gpt4 book ai didi

c - C 中的 remove() 返回 "No such file or directory"

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:45 24 4
gpt4 key购买 nike

我已经面对这个问题大约 2 周了,通过我所做的所有搜索(请注意,这已经非常广泛),我还没有找到解决方案。这是我的功能:

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 服务器的一部分,其中客户端可以输入的命令之一是从服务器存储(这是一个标记为“.storage/”的文件夹)中删除特定文件在我的硬盘上)。 fileExists()函数的代码如下:

int fileExists( char *fileName ) {
struct stat buf;
return ( stat( fileName, &buf ) == 0 );
}

当我运行我的代码并告诉服务器删除一个文件(我知道该文件确实存在)时,remove() 函数返回错误“没有这样的文件或目录”(在我的代码的旧版本我使用 perror() 来找出错误是什么)。但是,fileExists() 函数返回 0,表示该文件确实存在。

有没有人遇到过 stat() 报告文件存在但 remove() 不存在的问题?我真的很想弄清楚这个问题,但我还没有找到解决方案。非常感谢任何帮助。

编辑:感谢您的回复。事实证明,remove() 似乎不喜欢我发送给它的字符串上的空终止符。但是,我同意我的 fileExists() 函数有点误导。我会更改它以使其更容易(如果只是为了我自己的话)。

最佳答案

这是stat的手册..

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

您正在检查您的函数是否返回零..

int fileExists( char *fileName ) {
struct stat buf;
return ( stat( fileName, &buf ) == 0 );
}

假设一个文件存在..那么你的返回条件将返回 true(非 NULL 值)因为 stat 将返回 0 并且满足条件..但是这个检查显然是真的..

if ( fileExists( fileName ) != 0 ) {

并且你的男女同校打印出“错误文件不存在”..

将您的条件更改为

if ( fileExists( fileName ) == 0 ) {

关于c - C 中的 remove() 返回 "No such file or directory",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23236828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com