在C中将字节数组写回磁盘上的原始状态

在C中将字节数组写回磁盘上的原始状态,c,arrays,linux,C,Arrays,Linux,这对大多数人来说似乎没什么用,但我正试图找出如何将字节数组写回它曾经所在的原始文件,而不是在内存中执行(在内存中执行时发现了大量信息)。 特别是,如何在linux上用C实现这一点 我已将linux程序“touch”转换为字节数组: char touch[] = { 0x7F,0x45,0x4C,0x46,0x02,0x01,0x01,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x3E,0x00,

这对大多数人来说似乎没什么用,但我正试图找出如何将字节数组写回它曾经所在的原始文件,而不是在内存中执行(在内存中执行时发现了大量信息)。 特别是,如何在linux上用C实现这一点

我已将linux程序“touch”转换为字节数组:

    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,
    0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x68,0x64,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x40,0x00,0x38,0x00,0x09,0x00,0x40,0x00,
    0x1E,0x00,0x1D,0x00,0x06,0x00,0x00,0x00,0x05,0x00,
etc..
因此,我基本上只是尝试将touch作为newtouch写入当前目录

在windows中,我找到了CreateFile函数。open()在linux上是等效的吗


任何帮助都会很好。谢谢

只需使用
fwrite
编写数组,以二进制方式打开文件(在Linux上没有问题,但是文本/默认模式会在Windows上由于端行转换而创建损坏的二进制文件)

// 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);
#包括
const char touch[]={
0x7F,0x45,0x4C,0x46,0x02,0x01,0x01,0x00,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;
文件*f=fopen(“xxx”,“wb”);
如果(f!=NULL)
{
写入的大小=写入(触摸,触摸的大小,1,f);
如果(已写入!=1)
{
fprintf(stderr,“磁盘写入问题”);
}
其他的
{
rc=0;
}
fclose(f);
}
其他的
{
fprintf(stderr,“无法创建文件”\n);
}
返回rc;
}

在这里,我可以使用
sizeof(touch)
来获得合适的大小,因为
touch
是一个数组,而不仅仅是数据指针。

你知道
fopen()
?最好使用二进制模式
fopen(“文件名”,“wb”)
fputs(array)
假设
array
是一个字符串。
fputs
将在第一个零处停止。提示:
fwrite()
。谢谢,这正是我要找的,不多不少:)
#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;
}