【问题标题】:How to convert array of char to variable long in C?如何在C中将char数组转换为变量long?
【发布时间】:2012-10-17 19:35:24
【问题描述】:

我已经尝试了几个小时来转换它。我尝试循环遍历将字符转换为长整数的数组,但这不起作用。我在网上看到过简单的例子,但它们没有涵盖更长的 char 数组的循环过程。我可以使用什么方法将这个 char (SAMPLE) 数组转换为一个 long 类型的变量?

ar.h

struct  ar_hdr       /* file member header */
     {
         char    ar_name[16];    /* '/' terminated file member name */
         char    ar_date[12];    /* file member date */
         char    ar_uid[6]       /* file member user identification */
         char    ar_gid[6]       /* file member group identification */
         char    ar_mode[8]      /* file member mode (octal) */
         char    ar_size[10];    /* file member size */
         char    ar_fmag[2];     /* header trailer string */
     };

我的代码

struct ar_hdr sample;
lseek(fileD, 24, SEEK_SET); //fileD is the file desriptor for the opened archive

//I start at 24 because of the 8 byte magic string for an archive starts the file "!<arch>\n"


int numRead = read(fileD, sample.ar_date, 12);
printf(sample.ar_date);

long epoch = (long *) *sample.ar_date;   //terrible coding here
printf("The current time is: %s\n", asctime(gmtime(&epoch)));

【问题讨论】:

  • 你想做什么?文件中的每四个/八个字节代表一个long还是什么?
  • 如果字符表示十进制格式的字符串,使用atol函数
  • 你为什么要分配 epoch,一个 long 的变量,带有一个指向 long 的指针?另外,我猜 ar_date 是一个指针……但是指向什么的指针呢?字符?
  • 请贴出ar_hdr的定义
  • 字节 24 到 36 表示 unix 中标头 ar.h 的数据。这就是为什么我使用 lseek 从 24 开始并且只读取 12 个字节的原因。 ar_date 是指向 ar.h 结构 ar_hdr 中的变量的指针

标签: c long-integer typeconverter arrays


【解决方案1】:

man ar 说:

文件成员标题中的所有信息都采用可打印的 ASCII。这 标题中包含的数字信息以十进制形式存储 数字(八进制的 ar_mode 除外)。因此,如果存档 包含可打印文件,存档本身是可打印的。

所以 atol(ar_date) 应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    相关资源
    最近更新 更多