can I open a file and then close it in a loop? I tried but it doesnt seem to work. :(

Dani AI

Generated

Short answer: yes — you can open and close a file inside a loop. The behavior you saw is usually caused by not checking error returns, reusing a stream object without clearing its error flags, or by OS/file-permission issues. 's idea of opening once and closing once is valid if the file should stay open across iterations; if you need fresh opens each pass, open/close inside the loop.

A minimal C example (open, check, use, close each iteration):

for (int i = 0; i < 10; ++i) {
    FILE *f = fopen("data.txt", "r");
    if (!f) {
        perror("fopen");
        continue;
    }
    /* read from f */
    fclose(f);
}

In C++ prefer RAII — construct an ifstream inside the loop so it closes automatically:

for (int i = 0; i < 10; ++i) {
    std::ifstream in("data.txt");
    if (!in) {
        std::cerr << "open failed\n";
        continue;
    }
    std::string line;
    while (std::getline(in, line)) {
        /* process line */
    }
    /* in closed on scope exit */
}

If reusing a single std::ifstream/std::fstream object, call close() and then clear() before open() again, otherwise open() can fail due to previous flags.

Troubleshooting checklist:

  • Always check fopen/stream bool result and use perror/errno or std::error_code to see why it failed.
  • Verify the working directory and file path.
  • Ensure file permissions and that another process doesn't hold an exclusive lock.
  • If performance matters, open once outside the loop instead of repeated open/close.

See the standard docs for details: fopen documentation and std::ifstream::open.

(Contrary to , C/C++ do allow repeated fopen/fclose calls.)

Recommended Answers

All 2 Replies

Depens on when you're interrested in loading and closing it; but something like this:

for (int a=0; a<=10;a++)
  {
  if (a==0){LOAD}
  // Some stuff
  if (a==10){CLOSE}
  }

Something like this?

can I open a file and then close it in a loop? I tried but it doesnt seem to work. :(

No, I dont think C/C++ allow you to use fopen/fclose in a loop. If you use Linux, try "man-ing" fopen for more info:

man 3 fopen

hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.