【问题标题】:How to name and create file in a loop如何在循环中命名和创建文件
【发布时间】:2012-11-17 16:41:21
【问题描述】:

在 C 中,我想创建并打开文本文件以将数据写入其中,但问题是我想在旅途中为文件命名,例如

FILE *ptr;

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

这样我将创建文件 0.txt、1.txt、2.txt ... 999.txt。

这怎么可能?我检查了打开和重命名函数,但找不到方法。

非常感谢您的帮助。 最好的,

【问题讨论】:

    标签: c stdio


    【解决方案1】:

    使用snprintf设置文件号:

    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);
    }
    

    【讨论】:

    • FILENAME_MAX 比魔法常数 256 更合适。
    • 谢谢,但是当我在 VS 2008 中运行时,我收到以下错误::错误 LNK2019:未解析的外部符号 _snprintf 在函数 _main 中引用:致命错误 LNK1120:1 未解析的外部你知道我应该怎么做?
    • @user1450005 试试_snprintf_snprintf_s
    • thanks _snprintf 工作,但第一个问题仍然存在,它只创建一个文件,具有垃圾名称,第一个文件应该是 0.txt 但它创建 24322525.txt 这是不正确的,不会创建一个新文件,感谢您的帮助,谢谢
    • 您认为 snprintf 能完成所需的工作吗?
    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2018-03-21
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多