我想這樣做:在一個循環中,第一次迭代將一些內容寫入名爲file0.txt的文件,第二次迭代file1.txt等,只需增加數量。如何在循環中寫入時動態更改文件名?
char filename[16];
sprintf(filename, "file%d.txt", k);
file = fopen(filename, "wb"); ...
(儘管這是一個C溶液,使該標記是不正確的)
我想這樣做:在一個循環中,第一次迭代將一些內容寫入名爲file0.txt的文件,第二次迭代file1.txt等,只需增加數量。如何在循環中寫入時動態更改文件名?
char filename[16];
sprintf(filename, "file%d.txt", k);
file = fopen(filename, "wb"); ...
(儘管這是一個C溶液,使該標記是不正確的)
int k = 0;
while (true)
{
char buffer[32]; // The filename buffer.
// Put "file" then k then ".txt" in to filename.
snprintf(buffer, sizeof(char) * 32, "file%i.txt", k);
// here we get some data into variable data
file = fopen(buffer, "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file);
k++;
// here we check some condition so we can return from the loop
}
FILE *img;
int k = 0;
while (true)
{
// here we get some data into variable data
char filename[64];
sprintf (filename, "file%d.txt", k);
file = fopen(filename, "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file);
k++;
// here we check some condition so we can return from the loop
}
使用的sprintf這樣創建的文件名它在C++中:
#include <iostream>
#include <fstream>
#include <sstream>
int main()
{
std::string someData = "this is some data that'll get written to each file";
int k = 0;
while(true)
{
// Formulate the filename
std::ostringstream fn;
fn << "file" << k << ".txt";
// Open and write to the file
std::ofstream out(fn.str().c_str(),std::ios_base::binary);
out.write(&someData[0],someData.size());
++k;
}
}
一種不同的方式來做到:
FILE *img;
int k = 0;
while (true)
{
// here we get some data into variable data
file = fopen("file.txt", "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file);
k++;
// here we check some condition so we can return from the loop
}
不錯的解決方案,與我一起工作:) – 2014-02-20 22:16:59
我以下面的方式完成了這項工作。請注意,與其他一些示例不同,這將實際上按照預期進行編譯和運行,除了預處理器包含之外,沒有任何修改。下面的解決方案迭代了五十個文件名。
int main(void)
{
for (int k = 0; k < 50; k++)
{
char title[8];
sprintf(title, "%d.txt", k);
FILE* img = fopen(title, "a");
char* data = "Write this down";
fwrite (data, 1, strlen(data) , img);
fclose(img);
}
}
你的意思是51名:0和50每個都算作一個名字(不知道哪一個是你忘記考慮的名字)。你可以很快看到這一點,注意到從0到10(<11)實際上有11個名字。 – insaner 2015-03-28 10:16:11
我明白了。它的固定。 – 2015-07-19 02:50:41
+1''snprintf' over'sprintf'。 – 2010-11-20 13:12:02