【发布时间】:2020-08-14 11:23:24
【问题描述】:
我正在尝试通过 TCP 连接传输文件,我注意到 Mac 上的二进制/可执行文件没有文件扩展名。从现有二进制文件读取时,这似乎不是问题,但是当尝试写入新文件时,它会创建一个没有扩展名的空白文件 - 什么都没有。我怎样才能解决这个问题?代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char* filename = "helloworld";
FILE* file = fopen(filename, "rb");
FILE* writefile = fopen("test", "wb");
fseek(file, 0, SEEK_END);
unsigned int size = ftell(file);
printf("Size of %s is: %d bytes\n", filename, size);
fseek(file, 0, SEEK_SET);
char* line = (char *) malloc(size+1);
fread(line, size, 1, file);
fwrite(line, size, 1, writefile);
free(line);
fclose(writefile);
fclose(file);
return 0;
}
helloworld 是我正在读取的现有可执行文件(正在运行),我正在尝试写入一个名为 test 的新可执行文件
【问题讨论】:
-
首先您需要检查
fopen是否失败并采取相应措施。没有理由不这样做。 -
您还应该检查
malloc是否失败、fread是否失败或fwrite是否失败。如果fseek失败。 -
@它工作得很好
-
@Ry- 他们都工作
-
@Serket:不检查你怎么知道?显然有些东西不起作用,因为您得到的是一个空白文件,而且您不希望这样做。
标签: c macos file executable fopen