1

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?

  • You can use `mkdir` to make the local folder. See http://stackoverflow.com/questions/7430248/how-can-i-create-new-folder-using-c-language – lurker Oct 07 '13 at 02:09

2 Answers2

1

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;
}
Floris
  • 45,857
  • 6
  • 70
  • 122
  • Doesn't that make the directory protected? –  Oct 07 '13 at 02:41
  • @CharlieK - you are right, I was a bit too quick posting my answer; you can add the second parameter `0700` to set it with all permissions for the file owner (and none for anyone else). Answer edited accordingly - and updated to give a "complete, working code". – Floris Oct 07 '13 at 03:54
0
int k;

char filename[200];

for(k = 0; k < 10; k++)
{
    sprintf(filename, "/home/ubuntu/Desktop/%d.txt", k);
    fopen(filename,"w");
}
Duck
  • 26,924
  • 5
  • 64
  • 92