【问题标题】:File isn't removed using remove() function in c文件未使用 c 中的 remove() 函数删除
【发布时间】:2013-03-14 09:54:53
【问题描述】:

我已经编写了一个 C++ 库来使用 Visual C++ 2005 中的 remove 函数删除文件。但它不会删除文件。我该如何解决这个问题?

示例代码如下:

FILE *fp;
char temp[10000];
char *filename;

GetCurrentDirectoryA(10000,temp);
strcat(temp,"\\temp.png");

filename = (char*)malloc(sizeof(char)*strlen(temp));
memset(filename,'\0',strlen(temp));
strcpy(filename,temp);

if(png == NULL)
    return LS_ARGUMENT_NULL;

fp = fopen(filename,"wb");
fwrite(png,sizeof(unsigned char),pngLength,fp);
fclose(fp);

result = remove(filename);

【问题讨论】:

  • 一方面,filename 缓冲区太短了一个字符。您没有为空终止符留出空间。

标签: c++ c visual-c++-2005


【解决方案1】:

忽略其他部分,我认为你应该多分配一个字符:

filename = (char*)malloc(strlen(temp)+1); // I added a +1 for last '\0'
// memset(filename,'\0',strlen(temp));    // You dont need this
strcpy(filename, temp);

如果您需要从当前目录中删除文件,只需名称即可:

remove("temp.png");

去掉那些GetCurrentDirectoryA和相关代码。

【讨论】:

    【解决方案2】:

    1) char * strcat ( char * 目标, const char * 源); 连接字符串 将源字符串的副本附加到目标字符串。目标中的终止空字符被源的第一个字符覆盖,并且在目标中由两者连接形成的新字符串的末尾包含一个空字符。

    所以你不需要附加 NULL \0 字符

    2) 要使删除工作,您需要具有文件权限。检查一下。

    3) 使用 strerror(errno) 检查错误并打印错误

    如果 fopen 成功,您的代码似乎也不会检查

    if( remove( "myfile.txt" ) != 0 )
    perror( "Error deleting file" );
     else
    puts( "File successfully deleted" );
    return 0;
    

    【讨论】:

    • 吹毛求疵:\0NUL 尽管它被称为空终止符; NULL 有所不同,这就是为什么我更喜欢使用 0-/零终止符。无论如何:+1
    【解决方案3】:

    使用GetCurrentDirectory 使其仅限于Windows没有意义。

    这是一个花哨的跨平台版本:

    #include <iostream>
    #include <fstream>
    
    int main()
    {
        char file[1024];
        char buffer[2048];
    
        // Get file name.
        std::cout << "Enter name of file to create: ";
        std::cin >> file;
    
        // Append .txt to file.
        sprintf(file, "%s.txt", file);
    
        // Create it.
        std::cout << "* Creating file: " << file << std::endl;
        std::ofstream out(file);
    
        // Write in it.
        std::cout << "Write in the file: (CTRL+Z to stop)" << std::endl;
        while (std::cin >> buffer)
        {
            out << buffer << std::endl;
        }
    
        // Close it.
        out.close();
    
        // Delete it.
        std::cout << "* Deleting file: " << file << std::endl;
        if (remove(file) != 0) std::cerr << "* Couldn't remove the file. Does the program have the required permissions?" << std::endl;
    }
    

    【讨论】:

    • 您的帖子似乎没有回答 OP 的问题。
    • @alk 文件名短一个字符,因此不是以空值结尾的事实已经在评论中介绍过。我只是收集了他应该如何正确删除文件的小版本。更重要的是,我想指出一个事实,remove() 不需要使用绝对路径。
    • 为什么在 C++ 代码中使用 sprintf;为什么不ostringstreamstringsprint 臭名昭著,通常在被禁止的功能列表中。 string{stream} 是 C++ 方式,并不危险。
    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多