开发者

How to create custom filenames in C?

开发者 https://www.devze.com 2022-12-22 18:38 出处:网络
Please see this piece of code: #include<stdio.h> #include<string.h> #include<stdlib.h>

Please see this piece of code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
    in开发者_如何学Ct i = 0;
    FILE *fp;
    for(i = 0; i < 100; i++) {
        fp = fopen("/*what should go here??*/","w");
        //I need to create files with names: file0.txt, file1.txt, file2.txt etc
        //i.e. file{i}.txt
    }
}


for(i = 0; i < 100; i++) {
    char filename[sizeof "file100.txt"];

    sprintf(filename, "file%03d.txt", i);
    fp = fopen(filename,"w");
}


Use snprintf() with "file%d.txt" andi` to generate the filename.


Look into snprintf.


char szFileName[255] = {0};
for(i = 0; i < 100; i++)
{
    sprintf(szFileName, "File%d.txt", i);
    fp = fopen(szFileName,"w");
}


This should work:

for(i = 0; i < 100; i++) {
    char name[12];
    sprintf(name, "file%d.txt", i);
    fp = fopen(name, "w");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消