0

I have a question here that I cant find anywhere. I have been looking for the longest and my professors are useless. I'm trying to create N amount of files inside a for loop in C. I've tried the following code...and clearly that doesn't work, how do i go about make these files inside a for loop?

int i;
int N = 10;
for(i = 0; i < N; i++)
{
    fopen(("file%d",i),"w");
}
3
  • proper grammer didnt allow me to put this portion up essentially i want to make the files file0, file1, file2....etc whatever N is. Commented Jul 19, 2014 at 19:03
  • Are you asking how to combine ints with strings or on how to create files? Not every C function lets you use formatted string syntax like printf, check out sprintf. Commented Jul 19, 2014 at 19:05
  • 2
    @BenjaminGruenbaum: sprintf can be dangerous (and is becoming deprecated). Should use snprintf Commented Jul 19, 2014 at 19:15

1 Answer 1

1

Try

 int i;
 const int N = 10;
 for(i = 0; i < N; i++) {
    char nambuf[32];
    snprintf (nambuf, sizeof(nambuf), "file%d", i);
    FILE* f = fopen(nambuf, "w");
    if (!f) {perror(nambuf); exit(EXIT_FAILURE);};
    // print something in f, like
    fprintf (f, "this is %s\n", nambuf);
    fclose(f);
 }

Read documentation of snprintf(3), fopen(3), fclose(3), perror(3) ...

snprintf is useful to fill a string buffer. fopen can take such a buffer. Errors could happen, so we test some of them (you should also test failure of fprintf & fclose but I am lazy for that) and use perror to report them.

Learn about asprintf and C dynamic memory allocation

Sign up to request clarification or add additional context in comments.

7 Comments

you are a genious!! it worked, thanks a lot. Seems like to do a simple task, takes much more lines to do in C.
Please take time to read more books about C. Study the source code of some existing free software....
Ive used all this stuff before, I just didnt think to put all of them together @gekannt and like i said, ive searched, but nothing came up like this anywhere
@StevenR: what source code of some free software in C have you looked into?
@BasileStarynkevitch i just google what im looking for, its always something very simple (thats the worst part) but if i understand your question correctly, ive looked at a lot of source code, but Ive just been brain fried past couple days, doing things in C i dont even know, I always tend to ask the very simple questions that i get stuck on. and deal with the hard problems myself
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.