c++cvisual-c++-2005

File isn't removed using remove() function in c


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

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.