【问题标题】:How to write to a new Mac binary/executable using fopen and fwrite? [duplicate]如何使用 fopen 和 fwrite 写入新的 Mac 二进制文件/可执行文件? [复制]
【发布时间】: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


【解决方案1】:

您的代码看起来不错(忽略缺少错误检查)。复制完成后,您需要添加x(可执行)权限。

您可以在终端输入chmod +x test

从程序内部:

#include <sys/types.h>
#include <sys/stat.h>

...

    fclose(writefile);
    fclose(file);
    chmod("test", S_IRWXU);
    return 0;
}

【讨论】:

  • 如果为空,添加可执行位不会使其不为空。
  • 谢谢,有没有办法通过 c 程序做到这一点?
  • @Serket:您在空白文件上运行了chmod +x 并且内容出现在其中?您最初是如何确定它是空白的?
  • @Serket 所以文件不是空白的??
  • @Serket:缺少文件扩展名并不是导致它无法运行的原因,并且无法运行也不会导致它为空白。如果将来要帮助遇到同样问题的人,您的问题可能应该重新措辞很多。不过,很高兴你得到了答案。
【解决方案2】:

这是 XY 问题的一个示例。你说这是关于编写文件并命名它,但你真正的问题是你无法执行输出文件。后者才是真正的问题。您可以通过使用 diff 比较两个文件来避免考虑 X。这会鼓励您考虑元 Y 的可能性(即权限)。

如果您的代码在输入文件上执行 stat,那么它可以为输出文件执行元函数,如 chmodutime,给定来自 stat 结构的值。

例如,如果您的代码包含以下内容:

struct stat stat_filename; /* filename is an unsuitable name for such a variable */
if (stat(filename, &stat_filename)) {
    perror("cannot stat input file");
    exit(1);
}

那么在你写完输出文件之后,你可以这样做:

if (chmod("test", stat_filename.st_mode)) { /* need variable to hold output filename */
    perror("cannot chmod output file");
    exit(1);
}

如果你这样做,那么输出文件将更接近输入文件的“镜像”副本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2013-12-02
    • 1970-01-01
    相关资源
    最近更新 更多