【问题标题】:.exe file throws exception when opening file.exe 文件在打开文件时抛出异常
【发布时间】:2010-11-30 03:31:03
【问题描述】:

我正在尝试用 c++ 编写一个 CGI 脚本,它打印反向网络路径(使用 traceroute) 从 Web 服务器到调用 CGI 脚本的客户端的 IP 地址。

当我在 Visual Studio 中运行程序时,它工作正常(创建进程,将结果打印到“C:/result.out”文件中,打开文件,打印文件中的每一行,关闭文件)但是在编译后并尝试仅运行其 .exe 文件,它会引发异常。我该怎么做才能使 .exe 正常工作? 请注意,我使用的是 Windows XP 和 Visual C++ 2008

代码如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>

int main()
{
    char *line, *command, *userIp;

    printf("Content-Type:text/html\n\n");
    printf("<html><head></head><br/>");
    printf("<body><br/>");

    line    = (char*)malloc(255*sizeof(char));
    command = (char*)malloc(10*sizeof(char));
    userIp  = (char*)malloc(30*sizeof(char));
    //userIp = getenv("REMOTE_ADDR"); // use a default IP until program works 
    strcpy(command,"tracert ");
    strcpy(userIp,"74.125.87.104");

    strcat(command,userIp);
    strcat(command," > C:/result.out");
    // create command "tracert 74.125.87.104 > C:/result.out"

    printf("%s",command);
    system(command);
    FILE *f;
    f = fopen("C:/result.out","r");  // open C:/result.out and read line - by - line
    strcpy(line,"");
    while(!feof(f)){
      fgets(line,255,f);
      printf("%s\n",line);
    }
    fclose(f);
    printf("<br/>Test running OK<br/>");
    printf("</body></html>");
    getch();
    return 0;
}

【问题讨论】:

  • 请问它抛出的异常是什么?
  • Im sorry, Im 不太擅长 C 语言中的异常处理,所以我无法弄清楚。它只提示我我的程序抛出了一个未处理的 win32 异常。尽管如此,我还是设法解决了我的问题。不过谢谢你的回复

标签: c++ file exe


【解决方案1】:

很可能您的网络服务器(正常)没有写入 c:\ 的权限。为临时文件使用适当的位置,或者让tracert 将结果流式传输回可执行文件,以便您可以捕获它们。

【讨论】:

【解决方案2】:

以下两行导致缓冲区溢出

strcat(command,userIp);
strcat(command," > C:/result.out");

所以这很可能是崩溃的结果。

请不要使用术语“异常”,除非抛出异常,因为您正在编写不太可能的 C 代码。所以也不例外。

而不是使用 system() 运行命令并将结果通过管道传输到文件,使用 popen() 命令,这将运行命令并将输出传输到可以像文件一样读取的流(但没有安全性写入文件系统的影响)。

FILE *f;
f = popen(command,"r");  // run the command. The std out goes to the FILE stream
    ^^^^^^
strcpy(line,"");
while(!feof(f)){
  fgets(line,255,f);
  printf("%s\n",line);
}
fclose(f);

【讨论】:

  • 首先,非常感谢您的建议。效果很好。
  • 其次,关于“异常”一词......我只使用它是因为 Visual Studio 不断弹出一个错误,说我的程序抛出了未处理的 win32 异常。对不起,如果这不正确,我只是说我的电脑提示:-??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-16
  • 2020-09-21
相关资源
最近更新 更多