简体   繁体   中英

Is there a way I can close a file? fclose does not work well

I working on a WinApi project that the user upload the file he wants to encrypt and then I'm writing data to this file.

So, everything works well, but when I'm editing the file and encrypting it, the file is still "open" in the background. I'm using fclose() but it still does not stop the file from being used in the background. When the file is open I can't remove it.

Here is my code:

void write_file_to_encrypt(char* path1)
{
    srand(time(0));

    int x = rand() % 34234;

    FILE* file;
    file = fopen(path1, "w");

    int _size = x;
    char* data = new char[_size + 1];

    if (fopen(path1, "w")) {
        GetWindowText(filechoosed, data, _size + 1);

        fwrite(data, _size + 1, 1, file);

        fclose(file);
    }

    return;
}

// Save
void save_file_to_encrypt(HWND hWnd)
{
    OPENFILENAME ofn;

    char file_name[100];

    ZeroMemory(&ofn, sizeof(OPENFILENAME));

    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = hWnd;
    ofn.lpstrFile = file_name;
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = 100;
    ofn.lpstrFilter = "All Files\0*.*\0";
    ofn.nFilterIndex = 1;

    GetSaveFileName(&ofn);

    write_file_to_encrypt(ofn.lpstrFile);
}
file = fopen(path1, "w");
...
if (fopen(path1, "w")) {

You're calling fopen() twice. Change the if statement to:

if (file) {

I changed "if" condition and changed place of fclose().

void write_file_to_encrypt(char* path1)
{
    srand(time(0));

    int x = rand() % 34234;

    FILE* file;
    file = fopen(path1, "w");

    int _size = x;
    char* data = new char[_size + 1];

    if (file != NULL) {
        GetWindowText(filechoosed, data, _size + 1);

        fwrite(data, _size + 1, 1, file);

    }
    fclose(file);

    return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM