0

I'm trying to figure out a way to create a loop to open files and read in data until either there are no more files or the user wants to stop.

for example, the first time through the loop, the string variable would be "myfile_1" and then each subsequent time through the loop, the number will increase by 1. i.e. the next file would be "myfile_2" and so on.

So what would answer my question is, how can i open a file using a variable, and then change the file name to increment indefinitely?

I found this post but i'm still a little unclear, http://www.daniweb.com/software-development/c/threads/17594

2
Contributors
2
Replies
5
Views
5 Years
Discussion Span
Last Post by logicmonster
0
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string filename = "myfile_";
    
    for (int i = 1; i < 10; i++) {
        std::ostringstream oss;
        
        oss << filename << i;
        std::cout << oss.str() << '\n';
    }
}

Edit: My bad, I didn't realize this was the C forum. See below:

#include <stdio.h>

int main()
{
    const char *filename = "myfile_";
    int i;
    
    for (i = 1; i < 10; i++) {
        char buf[BUFSIZ];
        
        sprintf(buf, "%s%d", filename, i);
        printf("%s\n", buf);
    }
    
    return 0;
}

Edited by Narue: added a C solution

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.