如何使用fopen和fwrite写入一个新的Mac binaryexecutable?[重复]

问题描述 投票:0回答:1

我试图通过TCP连接传输文件,我注意到Mac上的binaryexecutable文件没有文件扩展名。当从现有的二进制文件读取时,这似乎不是一个问题,但当试图写入一个新的文件时,它会创建一个没有扩展名的空白文件,什么都没有。我如何解决这个问题?下面是代码。

#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

c macos file executable fopen
1个回答
0
投票

你的代码看起来很好(忽略缺乏错误检查)。 你需要添加 x (可执行文件)的权限。

在终端上,你可以输入 chmod +x test.

从程序内。

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

...

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

0
投票

这是一个XY问题的例子。你说是写文件和命名的问题,然而你真正的问题是不能执行输出文件。后者才是真正的问题。你本可以避免考虑X,通过使用 diff 来比较这两个文件。这将鼓励你考虑元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);
}

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

© www.soinside.com 2019 - 2024. All rights reserved.