2

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

示例代码如下:

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);
4

3 回答 3

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;
于 2013-03-14T10:04:11.463 回答
2

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

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和相关的代码。

于 2013-03-14T09:58:20.080 回答
0

使用GetCurrentDirectory. _

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

#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;
}
于 2013-03-14T10:16:02.577 回答