How to use index in the file name

前端 未结 4 1571
迷失自我
迷失自我 2021-01-24 09:12

This is probably trivial question. I am not a professional programmer, I am rather a mathematician who is doing some numerical experiment using C. I would like the output of my

4条回答
  •  孤独总比滥情好
    2021-01-24 09:44

    You could try this:

    #include 
    #include 
    
    int main(void) {
    
       int i = 0;
       for (i = 0; i < 10; i++) {
          char filename[64];
          sprintf(filename, "file%d", i);    
          FILE *fp = fopen(filename, "w");
          fprintf(fp, "%d\n", i);
          fclose(fp);
       }
       return 0;
    }
    

    Your code is almost ok. Some observations:

    • Use sprintf to create the name of the file. In C there is not a concatenate operator of strings.
    • You don't need to create an array of file pointers.
    • And of course, this may be improved: handling the size of the filename, padding the numbers, etc.

提交回复
热议问题