在C中复制的文件不工作
我试图用C语言创建一个程序,它在命令行中接收一个文件路径作为参数,并复制它。这是我的消息来源在C中复制的文件不工作,c,C,我试图用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 pat
#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在我的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)
(同样,这也没什么区别,但您应该使用getc
和putc
。您使用fgetc
和fputc
有什么原因吗?)- 使用while((c=(fgetc(fsource))!=EOF)
- 首先,它将从文件中获取值并与
进行比较,如果不是EOF
,则复制到变量(c)EOF
- 阅读
fgetc()
和fputc()
可以使用。@exophrenik用你的另一个问题更新了这个答案。非常感谢。是EOF中的打字错误破坏了可执行文件。fclise(fshellcode;
肯定是错误的。剪切并粘贴真实的代码。文件除了数据之外还有属性。也许你还需要某些权限。fgetc的使用()
要检索源文件,逐字节检查EOF将无法正常工作。建议使用:`fp=fopen()然后,fseek(fp,0,SEEK_END)然后,long bytesInFile=ftell(fp)然后,fseek(fp,0,SEEK_SET)然后,在循环中:fread(),fwrite()直到传输的总字节数等于字节数。确保始终检查函数返回值以捕获任何错误
while ((c = (fgetc(fsource)) != EOF)