我正在尝试将控制台输出写入文件。该文件已成功创建,但是没有任何内容写入该文件。下面是我的代码。
void AtoB(char * input)
{
unsigned int ascii; //used to store ASCII number of a character
int length = strlen(input);
for(int x=0;x<length;x++) //repeat until the input is read
{
ascii = input[x];
bin(ascii);
freopen("D:\\Testfiles\\Output1.txt","w",stdout);
}
}
void bin(unsigned n)
{
unsigned i;
for (i = 1 << 7; i > 0; i = i / 2)
{
//(n & i)? cout<<"1":cout<<"0";//printf("1"): printf("0");
(n & i)?printf("1"): printf("0");
}
}
我尝试了 printf 和 cout。文件已创建,但没有任何内容写入文件。我究竟做错了什么?还有其他方法可以将这些值写入文件吗? 注意:我在 Win 7 上使用 VS 2010 谢谢。
最佳答案
按照循环中的代码:
for(int x=0;x<length;x++)
{
// Retrieve a value
ascii = input[x];
// Write it to stdout
bin(ascii);
// Open the file, truncate it, and redirect stdout to it.
freopen("D:\\Testfiles\\Output1.txt","w",stdout);
}
由于您做的最后一件事是打开文件并截断它,因此您只剩下一个空文件。
在循环之前移动 freopen
- 你只需要做一次:
freopen("D:\\Testfiles\\Output1.txt","w",stdout);
for(int x=0;x<length;x++) //repeat until the input is read
{
ascii = input[x];
bin(ascii);
}
关于c++ - 无法将控制台输出写入 C 或 C++ 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634480/