我正在尝试添加一个具有 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;
}