Question

I have written a c++ library to remove a file using remove function in Visual C++ 2005. But it doesn't remove the file. How can I resolve this problem?

The sample code is given below:

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);
Was it helpful?

Solution

Ignoring other parts, I think you should allocate one more character:

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

If you need to remove a file from current directory just the name is enough:

remove("temp.png");

Get rid of those GetCurrentDirectoryA and related codes.

OTHER TIPS

1) char * strcat ( char * destination, const char * source ); Concatenate strings Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

So u need not need to append NULL \0 character

2) For remove to work, u need to have file permission. Check it.

3) Check for errors and print error using strerror(errno)

Also ur code doesn't seem to chek if fopen is successful

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

Theres no point in making it windows only by using GetCurrentDirectory.

Heres a fancy cross-platform version:

#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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top