Getting Errno::EMFILE when saving to file continuously

Hello.

I have a code to compile certain information as a text and save it in a file every specified period of time, line after line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void compileInformation()
{
    // Getting info here
    std::string flightInformationMessage =  "FD:" +
                                            boost::lexical_cast<std::string>(timeElapsed) + ":" +
                                            boost::lexical_cast<std::string>(altitudeCurrent) + "\n";
    
    
    /* Get current working directory */
    #ifdef __linux__
        char *dir = getcwd(NULL, 0);
    #elif __APPLE__
        char *dir = getcwd(NULL, 0);
    #elif _WIN32
        char *dir = _getcwd(NULL, 0);
    #endif
    
    // Identifying error
    if(dir == NULL)
    {
        perror("getcwd() error");
        std::string errorMessage = std::strerror(errno);
    }
    
    // Saving working directory as a string
    std::string workDirectory(dir);
    
    // Create the file name using the plane type, date and time
    std::string fileName =  "flight_report.igd";
    
    std::string reportFilePath = workDirectory + "/myFolder/" + fileName;
    
    std::ofstream ofs(reportFilePath.c_str(),ios::app);
    
    // Create a new file if it does not exist
    if (!ofs.is_open())
    {
        // Create out stream
        std::ofstream outfile(reportFilePath);
    }
    
    // When the file is created
    if (ofs.is_open())
    {
        // Save the report text
        ofs << flightInformationMessage;

        // Close the file
        ofs.close();
    }
}
    


In about 20-25 minutes, the program crashes with the following errno: "Too many open files". I do not understand why, since I am closing the file. I am using Mac, but this is supposed to be a multiOS plugin.

I would greatly appreciate if someone could help. Thanks!
The file is closed in any event, the call to ofs.close() is redundant. Do you open files anywhere else?
Thanks. Just wanted to make sure that the code had no issues. The culprit is probably my client that I wrote in Java. Will be checking that. Thank you again!
Topic archived. No new replies allowed.