c++ - 无法将控制台输出写入 C 或 C++ 文件

标签 c++ c

我正在尝试将控制台输出写入文件。该文件已成功创建,但是没有任何内容写入该文件。下面是我的代码。

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/

相关文章:

c++ - 如何检查构造函数/析构函数中是否使用了虚方法?

c++ - 如何重定向在 C++ 中读取 bash 脚本的输出?

c - 特定于体系结构的 header

c - 从 Postgres C 函数返回一个数组?

c - 在 C 中释放内存时应考虑哪些主要事项?

c - K&R 2-8 右旋转(整数长度,以位为单位)

c++ - VSCode - C++ 未定义对 'CLASS::FUNCTION' 的引用

c++ - 命名空间和类成员

c++ - 将 unique_ptr 转换为 void* 并返回,我需要释放吗?

java - 如何在 JNA 中传递包含原始类型数组的结构?