首页 > 解决方案 > C 检查归档文件是否被 struct ar_hdr (ar.h) 截断

问题描述

我正在使用 ar.h 的结构:struct ar_hdr检索我的存档文件 (lib.a) 中的信息read,并对其进行迭代,如果文件被截断,我会遇到一个小问题。

在使用 C 语言时,当文件被截断时,它目前使我遇到分段错误。

有什么方法可以检查文件是否被预先截断?喜欢使用 stat 或类似的东西?

提前致谢

PS:如果我的问题不是很容易理解和清楚,请随时告诉我

#define SIZE atoi(ar->ar_size)

struct ar_hdr *get_header(int fd)
{
    struct ar_hdr *ar = (struct ar_hdr *)malloc(sizeof(struct ar_hdr));

    if (read(fd, ar, sizeof(struct ar_hdr)) != sizeof(struct ar_hdr)) {
        free(ar);
        return NULL;
    }
    return ar;
}
int handle_ar_files(int fd, char *names[2], int ret)
{
    struct ar_hdr *ar = NULL;
    void *buf = NULL;
    int index = 0;

    while ((ar = get_header(fd)) != NULL) {
        index = 0;
        buf = malloc(SIZE);
        if (ar->ar_name[0] == '/') {
            my_free(ar, buf, (int [2]){fd, SIZE}, 1);
            continue;
        }
        for (; ar->ar_name[index] && ar->ar_name[index] != '/'; index++);
        ar->ar_name[index] = 0;
        if ((read(fd, buf, SIZE)) != SIZE)
            return my_free(ar, buf, (int [2]){fd, SIZE}, 0);
        if ((parse_ar(buf, SIZE, (char *[2]){names[1], ar->ar_name})) == 84)
            return my_free(ar, buf, (int [2]){fd, SIZE}, 0);
        else
            my_free(ar, buf, (int [2]){fd, SIZE}, 0);
    }
    return ret;
}

void *buf32 = mmap(NULL, st->st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (strncmp((char *)buf32, ARMAG, SARMAG) == 0) {
        read(fd, tmp, SARMAG);
        return handle_ar_files(fd, names, 0);
}

#ifndef _AR_H
#define _AR_H 1

#include <sys/cdefs.h>

/* Archive files start with the ARMAG identifying string.  Then follows a
   `struct ar_hdr', and as many bytes of member file data as its `ar_size'
   member indicates, for each member file.  */

#define ARMAG   "!<arch>\n" /* String that begins an archive file.  */
#define SARMAG  8       /* Size of that string.  */

#define ARFMAG  "`\n"       /* String in ar_fmag at end of each header.  */

__BEGIN_DECLS

struct ar_hdr
  {
    char ar_name[16];       /* Member file name, sometimes / terminated. */
    char ar_date[12];       /* File date, decimal seconds since Epoch.  */
    char ar_uid[6], ar_gid[6];  /* User and group IDs, in ASCII decimal.  */
    char ar_mode[8];        /* File mode, in ASCII octal.  */
    char ar_size[10];       /* File size, in ASCII decimal.  */
    char ar_fmag[2];        /* Always contains ARFMAG.  */
  };

__END_DECLS

#endif /* ar.h */

标签: ctruncated

解决方案


推荐阅读