如何在C中创建自定义文件名?

时间:2010-03-15 06:03:52

标签: c string file-io fopen

请看这段代码:

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

int main() {
    int 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
    }
}

5 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分:1)

使用snprintf()"file%d.txt" and i`生成文件名。

答案 2 :(得分:1)

查看snprintf

答案 3 :(得分:1)

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

答案 4 :(得分:0)

这应该有效:

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