user2082839
user2082839

Reputation:

Naming a file with a loop counter

How do I write this line that runs in a loop and uses the loop counter k to give a file its name?

int k;
for(k = 0; k < 10; k++)
    fopen("/home/ubuntu/Desktop/" + k + ".txt", "w"); // java-like code

Also how can I create a folder on the local directory to put the files there instead of using the Desktop?

Upvotes: 1

Views: 278

Answers (2)

Floris
Floris

Reputation: 46435

There were two parts to your question: creating a directory, and writing numbered files. Try the following (updated so the directory protection is set explicitly, that correct headers are included, and that one file is closed before the next one is opened):

#include <stdio.h>
#include <sys/stat.h>

int main(void) {
  const char* myDirectory = "/Users/floris/newDirectory";
  char fileName[256];
  int ii, fErr;
  FILE *fp;
  fErr = mkdir(myDirectory, (mode_t)0700);
  for(ii=0; ii< 10; ii++) {
    sprintf(fileName, "%s/file%d.txt", myDirectory, ii);
    if((fp = fopen(fileName, "w"))!=NULL) {
      // do whatever you need to do
    }
    else {
      printf("could not open %s\n", fileName);
    }
    fclose(fp);
  }
return 0;
}

Upvotes: 1

Duck
Duck

Reputation: 27562

int k;

char filename[200];

for(k = 0; k < 10; k++)
{
    sprintf(filename, "/home/ubuntu/Desktop/%d.txt", k);
    fopen(filename,"w");
}

Upvotes: 0

Related Questions