我有两个问题,第一个已经解决了。
当前问题
如果我嵌入需要库加载的文件,例如jpeg图像或mp3音乐,我将需要将该文件作为库的输入。然而,每个库都是不同的,并且使用一种方法来获取文件作为输入,输入可能是文件名或FILE*指针(来自libc的文件接口)。
我想知道如何使用名称访问嵌入式文件。如果我创建一个临时文件,那将是低效的,是否有另一种方法?我可以将文件名映射到内存吗?我的平台是Windows和Linux。
如果show_file(const char* name)是从库中提取出的函数,那么我需要一个字符串来打开该文件。
我看过以下这些问题:
如何获得内存缓冲区的文件描述符?
从文件描述符中获取文件名(C语言)
下面的代码是我的解决方案。它是一个好的解决方案吗?它是否低效?
# include <stdio.h>
# include <unistd.h>
extern char _binary_data_txt_start;
extern const void* _binary_data_txt_size;
const size_t len = (size_t)&_binary_data_txt_size;
void show_file(const char* name){
FILE* file = fopen(name, "r");
if (file == NULL){
printf("Error (show_file): %s\n", name);
return;
}
while (true){
char ch = fgetc(file);
if (feof(file) )
break;
putchar( ch );
}
printf("\n");
fclose(file);
}
int main(){
int fpipe[2];
pipe(fpipe);
if( !fork() ){
for( int buffsize = len, done = 0; buffsize>done; ){
done += write( fpipe[1], &_binary_data_txt_start + done, buffsize-done );
}
_exit(0);
}
close(fpipe[1]);
char name[200];
sprintf(name, "/proc/self/fd/%d", fpipe[0] );
show_file(name);
close(fpipe[0]);
}
另一个问题(已解决)
我在Linux上使用GCC尝试嵌入文件,它成功了。但是,我在Windows上使用Mingw尝试做同样的事情时,它没有编译通过。
代码如下:
# include <stdio.h>
extern char _binary_data_txt_start;
extern char _binary_data_txt_end;
int main(){
for (char* my_file = &_binary_data_txt_start; my_file <= &_binary_data_txt_end; my_file++)
putchar(*my_file);
printf("\n");
}
编译命令为:
objcopy --input-target binary --output-target elf32-i386 --binary-architecture i386 data.txt data.o
g++ main.cpp data.o -o test.exe
在 Windows 上,我收到以下编译器错误:undefined reference to `_binary_data_txt_start'
undefined reference to `_binary_data_txt_end'
我试图用 i386-pc-mingw32 替换 elf32-i386,但是我仍然得到相同的错误。