How to name and create file in a loop

半腔热情 提交于 2020-01-01 15:32:42

问题


In C, I want to create and open text files to write data into, but the problem is I want to name the files on the go, such as

FILE *ptr;

for(i=0;i<1000;i++){
   fopen_s(&ptr,"i.txt","w");
   operations to fill data into file i.txt;
   fclose(ptr);
}

such that I will create file 0.txt, 1.txt, 2.txt ... 999.txt.

How is this possible? I checked open and rename functions, but couldn't find a way to do.

Thank you so much for all your help. Best,


回答1:


use snprintf to set the file number:

FILE *ptr;
char name[FILENAME_MAX];

for(i=0;i<1000;i++){
   snprintf(name, sizeof(name), "%d.txt", i);
   fopen_s(&ptr, name, "w");
   //operations to fill data into file i.txt;
   fclose(ptr);
}


来源:https://stackoverflow.com/questions/13432535/how-to-name-and-create-file-in-a-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!