0

我正在尝试添加一个具有 ar_hdr 格式的新文件成员,并将其放在存档中的最后一个元素之后。我的代码可以编译,但是当我想使用 ar -t 命令查看文件名时,我收到一条错误消息:ar: hello.a: Inappropriate file type or format。有人可以看看我的代码并给我一些关于如何修复它的提示吗?谢谢。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/utsname.h>
#include <ctype.h>
#include <string.h>
#include <ar.h>

#define BLOCKSIZE 1

int main (int argc, char **argv)
{
    char *archive = argv[1];
    char *read_file = argv[2];

    int in_fd;
    int out_fd;

    char title[] = ARMAG;   //constant define in ar.h
    char buf[BLOCKSIZE];

    int num_read;
    int num_written;

    struct stat stat_file;
    struct ar_hdr my_ar;

    //open read_file (i.e., text file)
    if (stat(read_file, &stat_file) == -1){
        perror("Error in Stat");
        exit(-1);
    }

    //assign file info to struct dhr (my_ar)    
    sprintf(my_ar.ar_name, "%s", read_file);
    sprintf(my_ar.ar_date, "%ld", stat_file.st_mtimespec.tv_sec);
    sprintf(my_ar.ar_uid, "%i", stat_file.st_uid);
    sprintf(my_ar.ar_gid, "%i", stat_file.st_gid);
    sprintf(my_ar.ar_mode, "%o", stat_file.st_mode) ;
    sprintf(my_ar.ar_size, "%lld", stat_file.st_size) ;


    //0666 - open archive
    out_fd = open(archive, O_CREAT | O_WRONLY | O_APPEND, 0666);
    if (out_fd == -1) {
        perror("Canot open/create output file");
        exit(-1);
    }

    //write my_ar to archive
    num_written = write(out_fd, title, sizeof(title));
    num_written = write(out_fd, &my_ar, sizeof(my_ar));


    printf("\n");

    return 0;
}
4

2 回答 2

0

title应该在文件的最开始出现一次。如果要将文件附加到存档,则只需ar_hdr为新文件编写 ,然后是文件的内容。

所以需要检查文件是否已经存在。如果没有,并且您正在创建一个新存档,则需要先编写title。如果确实存在,请跳过该步骤。由于您以附加模式打开文件,因此您可以使用以下命令判断它是否是新文件lseek()

off_t curpos = lseek(out_fd, SEEK_CUR, 0); // Get current position
if (curpos == 0) { // At beginning, it must be a new file
  num_written = write(out_fd, ARMAG, SARMAG);
}
于 2013-07-21T07:43:07.810 回答
0

user2203774,我要重申:您正在使用一种文档不完整且未标准化的文件格式。了解正确文件格式的唯一方法是(a)研究我在您的另一个问题中提供的文档链接,以及(b)分析您拥有的存档文件的样本,以确定格式是否符合此类文档就像你一样。可能是文件格式相似,但不完全相同。然后,您需要弄清楚差异是什么。一旦你这样做了,创建你自己的文件格式文档,然后处理它。

还请注意,第一个也是最简单的调试步骤是“将我的程序生成的arod -c内容与由.

几点:

  • 魔术头字符串 ( "!<arch>\n") 仅出现在文件的开头,而不是每条记录的开头。
  • 结构中的所有字段ar_hdr都用空格填充,并且不是以空值结尾的字符串。
  • 除非您准备更新符号表(包括在必要时添加一个)并重写整个文件,否则您必须确保文件名不超过 15 个字符。
  • 每个文件名后面必须紧跟一个/字符(后面不能跟 null。同样,该字段的其余部分用空格填充。)
  • 您永远不会初始化结构的ar_fmag字段ar_hdr。这需要初始化为特定值。
  • 写完header后,需要写文件的实际内容。
  • 一些参考资料表明,在写入文件内容时,必须写入偶数个字节。如果文件大小是奇数,\n则应附加一个作为填充(并且标题中记录的文件大小不会增加以包含填充字节)。
于 2013-07-22T16:41:23.390 回答