views:

156

answers:

5

Please see this piece of code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
    int i = 0;
    FILE *fp;
    for(i = 0; i < 100; i++) {
        fp = fopen("/*what should go here??*/","w");
        //I need to create files with names: file0.txt, file1.txt, file2.txt etc
        //i.e. file{i}.txt
    }
}
A: 

This should work:

for(i = 0; i < 100; i++) {
    char name[12];
    sprintf(name, "file%d.txt", i);
    fp = fopen(name, "w");
}
Kyle Lutz
A: 

Use snprintf() with "file%d.txt" andi` to generate the filename.

Ignacio Vazquez-Abrams
+3  A: 
for(i = 0; i < 100; i++) {
    char filename[sizeof "file100.txt"];

    sprintf(filename, "file%03d.txt", i);
    fp = fopen(filename,"w");
}
caf
notice how he put `%03d`. strictly speaking, you just need `%d` to do what you asked, but this will pad it to 3 digits with leading 0s, so that they will sorted properly by your OS (well... windows is kind of clever about that actually, but still, leading 0s are cool!)
Mark
A: 

Look into snprintf.

Laurynas Biveinis
A: 
char szFileName[255] = {0};
for(i = 0; i < 100; i++)
{
    sprintf(szFileName, "File%d.txt", i);
    fp = fopen(szFileName,"w");
}
YeenFei
uhm... me thinks you forgot to edit a line when you copy pasted ;)
Mark
thanks for the feedback, and its nice to be fast on down votes...maybe try reload answer faster next time
YeenFei
255 is quite a large buffer. At least your solution will do well for extremely large values of `i`.
dreamlax