Intermediate C++: Working with Temporary Files

Intermediate C++: Working with Temporary Files

1. Temporary Files

Everyone knows about temporary files; some data needs to be saved temporarily, and these temporary files are not particularly useful. However, it is precisely because they are not very useful that they are needed in certain scenarios. For example, some unimportant log data, some cached intermediate files, etc. These data will eventually generate persistent data or will quickly become useless, at which point these temporary files will no longer serve a purpose and will be deleted when certain conditions are triggered.Different platforms handle temporary files in different locations, but they can generally be easily identified. Common locations for temporary files are as follows:Windows platform: C:\Users\\AppData\Local\TempApple platform: /private/var/folders/ and ~/Library/Caches/Linux platform: /tmp/ and /var/tmp/

2. Handling Temporary Files During Development

When developing, if you encounter the need to handle temporary files, there are various methods to do so. The simplest method is to manually operate the traditional file system API to write to a specified location (including the system’s tmp folder) and delete it under appropriate conditions. However, this approach has a problem: different platforms may handle paths differently, making it difficult for maintainers or users to manage. Therefore, common libraries provide dedicated interfaces for handling temporary files, such as the tmpfile function and mkstemp, mkdtemp functions. The former creates temporary files that do not require manual maintenance by the developer and will be automatically deleted when the file stream is closed or the program terminates; while the latter creates temporary folders and files that require manual handling by the developer.This is somewhat similar to the handling methods of stacks and heaps that we learned before.

3. Application Scenarios for Temporary Files

The role of temporary files is quite significant, and common scenarios include:1. Caching: Browsers and software cache temporary data to improve processing speed (e.g., web cookies, photos, videos, etc.)2. Intermediate states of program execution: Unpacking software installation packages, auto-saved files during document editing, intermediate data during calculations, small files during segmented downloads of large files, etc.3. Temporary data for systems and users: OS update backups, logs, and inter-process communication via files, etc.Temporary files have exposed many issues during application, mainly including:1. Privacy leaks: Browser cookies, caches, and history, etc.2. Storage waste: A large number of temporary files that cannot be deleted in a timely manner occupy considerable hard disk space, such as the C drive in Windows often becoming full due to temporary files.3. System applications: Accidentally deleting certain temporary files can cause system applications to malfunction, for example, deleting temporary files while compiling a large project may lead to compilation errors.

4. Example Analysis

#include<stdio.h>
#include<stdlib.h>
int main(){
    FILE *tmp = tmpfile();
    if(tmp == NULL){
        return -1;
    }
    fprintf(tmp,"test temp data.\n");
    rewind(tmp);
    char buf[100];
    if(fgets(buf,sizeof(buf), tmp)!= NULL){
        printf("read buf: %s", buf);
    }
    fclose(tmp);
    return 0;
}

Now let’s look at using the mkstemp and mkdtemp functions to create temporary directories and files:

// Temporary directory
#include<iostream>
#include<cstdlib>
#include<sys/stat.h>// mkdir permissions
#include<cstring>
int main(){
    char tmpDirName[]="/tmp/dir_XXXXXX";// Template must end with 6 Xs
    if(mkdtemp(tmpDirName)==nullptr){
        return 1;
    }
    std::cout << "temp path: " << tmpDirName << std::endl;
    rmdir(tmpDirName);
    return 0;
}
// Temporary file
#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<cstring>
int main(){
    char tmpName[]="/tmp/testFile_XXXXXX";
    int fd = mkstemp(tmpName);
    if(fd == -1){
        perror("mkstemp failed");
        return 1;
    }
    const char* content = "test data!\n";
    write(fd, content, strlen(content));
    close(fd);
    unlink(tmpName);
    return 0;
}

In fact, there is another function in the C library called tmpnam that can be used to create different temporary file names, but it has many limitations, so it will not be introduced here. Those interested can look for relevant materials on their own.

5. Conclusion

Temporary files are an intermediate state in application processing. Generally, this intermediate state is unstable, so temporary files often imply that they may be cleaned up at any time. Developers should be adept at using this state to achieve some design goals, but they should never impulsively write important data into these temporary files.Developers should also have an eye for discovering beauty!

Leave a Comment