c - 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 */
解决方案
推荐阅读
- node.js - 使用 IBM Cloud Function 读取 gzip 文件 (.gz) 时出现问题(操作:Node.js 12)
- r - 聚合合作伙伴之间的交互模式
- javascript - 如何使用 setinterval 在 10 秒后自动获取更新的数据
- mysql - MySQL中的寻路
- r - group_map 的替代品
- unit-testing - 通过 cloudtest 进行单元测试时使用代码覆盖率运行时合并验证失败
- javascript - 我将如何使用 Jquery 在输入元素中显示我的数据输出
- java - 如何只允许用户在编辑文本中输入合理的身高和体重值?爪哇
- sql - 使用 IF 语句创建 VIEW(工作日案例)
- python - 无法在 python 中的两个多进程之间共享数据