这对大多数人来说似乎没用,但是我试图找出如何将字节数组写回原来的文件,而不是在内存中执行(发现有大量关于执行的信息)记忆)。 特别是,如何在Linux上使用C语言。
我已经转换了linux程序' touch'到一个字节数组:
file1.zip<br>
---file2.zip<br>
--- --- file3.txt<br>
--- --- file4.txt
所以我基本上只是尝试将touch作为newtouch写入当前目录。
使用Windows我找到了CreateFile函数。 open()是linux上的等价物吗?
任何帮助都会很棒。感谢
答案 0 :(得分:3)
只需使用fwrite
编写数组,将文件打开为二进制文件(在Linux上没有问题,但文本/默认模式因为终端转换而在Windows上创建损坏的二进制文件)
#include <stdio.h>
const char touch[] = {
0x7F,0x45,0x4C,0x46,0x02,0x01,0x01,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x3E,0x00,
0x01,0x00,0x00,0x00,0xA0,0x38,0x00,0x00,0x00,0x00};
int main()
{
int rc=1;
FILE *f=fopen("xxx","wb");
if (f!=NULL)
{
size_t written = fwrite(touch,sizeof(touch),1,f);
if (written != 1)
{
fprintf(stderr,"disk write issue\n");
}
else
{
rc = 0;
}
fclose(f);
}
else
{
fprintf(stderr,"cannot create file\n");
}
return rc;
}
我可以使用sizeof(touch)
来获得正确的大小,因为touch
是一个数组,而不仅仅是数据指针。
答案 1 :(得分:-2)
// Open a file for writing.
// (This will replace any existing file. Use "w+" for appending)
FILE *file = fopen("filename", "wb");
int results = fputs(array, file);
if (results == EOF) {
// Failed to write do error code here.
}
fclose(file);