gpt4 book ai didi

C 中复制的文件不起作用

转载 作者:行者123 更新时间:2023-12-04 11:58:02 25 4
gpt4 key购买 nike

我正在尝试用 C 语言创建一个程序,该程序在命令行中接收一个文件路径作为参数并复制它。这是我的来源。

#include <stdio.h>
#include <stdlib.h>


int main(int args, char* argv[])
{
if (args != 2)
{
printf("Error: Wrong number of arguments.\n");
printf("Enter the path of the file to be copied as the only argument.\n");
system("PAUSE");
return 1;
}
FILE *fsource;
FILE *fshellcode;

if((fsource = fopen(argv[1],"rb")) == NULL)
{
printf("Error: Could not open source file. Either the path is wrong or the file is corrupted.\n");
system("PAUSE");
return 2;
}

if((fshellcode = fopen("shellcode.exe","wb")) == NULL)
{
printf("Error: Could not create shellcode.exe file.\n");
system("PAUSE");
return 3;
}

char c;
while ((c = fgetc(fsource) != EOF))
{
fputc(c,fshellcode);
}
fclose(fsource);
fclise(fshellcode;
return 0;
}

当我输入工作 exe 的路径作为参数时,程序会正确创建 shellcode.exe 并将所有字节从源 exe 复制到其中。当我尝试执行新的 exe 时,我收到以下错误消息:

The version of this file is not compatible with the version of Windows you're running.

当源 exe 在我的 64 位 Windows 7 系统上正常运行时,这怎么可能?

最佳答案

一个问题是需要声明

int c;

这有什么不同?好吧,您读取的第一个字节值为 0xff(在 exe 之类的二进制文件中很快就会发生)可能会被符号扩展为 -1 并且看起来像 EOF。所以您可能不会复制整个文件。

然后第二个问题是你有一个有趣的拼写错误

while ((c = fgetc(fsource) != EOF))

!=的优先级高于=,所以编译器将其解释为

while (c = (fgetc(fsource) != EOF))

因此只要您读取非 EOF 字符,c 就会设置为 1。

你想要的是

while ((c = (fgetc(fsource)) != EOF)

(此外,这不会有什么不同,但您应该使用 getcputc。您使用 fgetc 有什么原因吗> 和 fputc?)

关于C 中复制的文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com