C 如何生成文件名序列
我希望向一个参数添加多个部分 像这样,我知道在VB.net中我可以做到C 如何生成文件名序列,c,string,C,String,我希望向一个参数添加多个部分 像这样,我知道在VB.net中我可以做到 messagebox("hello" + textbox1.text) // yields hello and whatever is in textbox1 但是在C语言中我该怎么做呢 我尝试了&和+,但它给了我错误 我想创建5个文件,并使用for循环创建它们,计数为1-5 ofp = fopen("data" + (loop counter) + ".txt", "r"); // allong those lines.
messagebox("hello" + textbox1.text) // yields hello and whatever is in textbox1
但是在C语言中我该怎么做呢
我尝试了&
和+
,但它给了我错误
我想创建5个文件,并使用for循环创建它们,计数为1-5
ofp = fopen("data" + (loop counter) + ".txt", "r"); // allong those lines...
所以文件名应该是data1.txt;data2.txt;data3.txt等等
谢谢在这种情况下,您可以使用snprintf:
char buffer[FILENAME_MAX];
snprintf(buffer,FILENAME_MAX,"data%d.txt",counter+1); //You will probably start counter at 0
buffer[FILENAME_MAX-1]=0;// snprintf may skip null terminator.
FILE* ofp=fopen(buffer,"w");
//...
fclose(ofp);
sprintf是生成filenamehelper所需的工具,类似strcpy的函数可以提供帮助。请参阅“如何向一个参数添加多个信息?”——对于这个问题,答案是“使用
结构”。您真正需要的是串接字符串。请不要重复问题标题中的标记。请查看snprintf()
的第二个参数可以是FILENAME\u MAX
(或者更好的是,sizeof buffer
)。