C ++在退出WINAPI之前将控制台输出保存到文本文件(无MFC)

时间:2012-05-23 13:44:49

标签: c++ winapi file-io console

我试图让我的程序在退出之前将控制台应用程序的输出记录到文本文件中。这是一个启动控制台应用程序(tool.exe)的GUI程序。问题是我使用CTRL + C退出控制台应用程序。此控制台应用程序也无法更改。我尝试了几种方法,但似乎没有任何方法(tool.exe> output.txt)。

有人能指出我采取哪种方法的正确方向?非常感谢。

修改

文件已创建,但文件为空且未收到任何数据。我注意到的事情是,如果我自己从命令行运行该工具,它将工作。例如。 c:\>tool.exe > output.txt然而,当它从我的GUI应用程序执行时,这不起作用。

以下是我用来执行该工具的代码:

    strcpy (tool, "\" start /D \"");
    strcat (tool, toolLocation);
    strcat (tool, "\" tool.exe > output.txt\"");
    system (tool);

这将运行tool.exe并创建output.txt,但不会向文件输出任何内容。

EDIT2:

我认为实际发生的是因为我使用的是start>output.txt正在输出start而不是tool.exe。这可以解释为什么它会创建空文件。 Start就是运行一个新的命令行,然后运行tool.exe。问题是,我现在如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

尝试:

#include <signal.h>
void signal_handlerkill(int sig)
{
  //Do Soemthing
  exit(1);
}

int main()
{
  signal(SIGINT, signal_handlerkill); //Connect the interrupt signal (^C) to the function
  //Do your code here
  return 0;
}

如果这不起作用,我建议寻找here。具体做法是:

// crt_signal.c
// compile with: /c
// Use signal to attach a signal handler to the abort routine
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <tchar.h>

void SignalHandler(int signal)
{
    printf("Application aborting...\n");
}

int main()
{
    typedef void (*SignalHandlerPointer)(int);

    SignalHandlerPointer previousHandler;
    previousHandler = signal(SIGABRT, SignalHandler);

    abort();
}

答案 1 :(得分:0)

如果在不重定向到文件的情况下运行应用程序,当按ctrl + c时,是否在控制台上看到了所需的输出?

如果不这样做,那么由于无法更改应用程序,因此无法执行任何操作。

<强>更新

您需要将stdout和stderr重定向到该文件。我从来没有这样做,但詹姆斯林似乎已经这样做了。看看他的评论。

您可以尝试的是直接使用start而不是cmd.exe尝试。

答案 2 :(得分:0)

这是为我解决问题的代码:

            char path[500]; //Create character array
            strcpy (path, "cd "); //Copy 'cd' into the array
            strcat (path, toolLocation); //Copy the path of the tool into the array
            strcat (path, " & ip.exe > output.txt"); //Append on the name of the exe and output to a file
            system (path); //Run the built array

我正在创建一个字符数组然后追加它。这里的重要位是系统调用中使用的&。这是作为and工作,并在执行.exe之前首先进入firectory。