这是一项任务(不是我的,而是我正在帮助的人,如果这很重要的话),但应该编写一个模仿 unix ar 命令的程序。我非常接近于使用 stat() 函数将文件信息写入 header ,但是在写入文件时我得到的是 @^ 而不是空格。
这是一个输出示例
1-s.txt2^@^@^@^@^@^@^@^@10 月 30 日星期三 149972^@14601^@100640^@^@101^@^@^@^@^@^ @^@
它应该是
1-s.txt2/10 月 30 日星期三 149972 14601 100640 101
除了日期应该是一个 unix 时间戳,任何帮助也将不胜感激。
谢谢!!!
struct ar_hdr headerstruct;
void setfileinfo(const struct stat *sfileinfo){
sprintf(headerstruct.ar_name, "%s", global_argv[3]);
sprintf(headerstruct.ar_date, "%s", ctime(&sfileinfo->st_mtime));
sprintf(headerstruct.ar_uid, "%ld", (long)sfileinfo->st_uid);
sprintf(headerstruct.ar_gid, "%ld", (long) sfileinfo->st_gid);
sprintf(headerstruct.ar_mode, "%lo",(unsigned long)sfileinfo->st_mode);
sprintf(headerstruct.ar_size, "%lld",(long long)sfileinfo->st_size);
char filemag[2] = "`\n";
int fd;
fd = open(global_argv[2], O_RDWR);
lseek(fd, 0, SEEK_END);
write(fd, headerstruct.ar_name, 16);
write(fd, headerstruct.ar_date, 12);
write(fd, headerstruct.ar_uid, 6);
write(fd, headerstruct.ar_gid, 6);
write(fd, headerstruct.ar_mode, 8);
write(fd, headerstruct.ar_size, 10);
write(fd, filemag ,2);
return;
}
最佳答案
由于 ar
header 需要空格填充,您可以考虑使用 memset
为数据结构或特定成员预填充空格。例如:
memset(&headerstruct, ' ', sizeof(headerstruct));
此外,如果你想避免在 header 中以空字符结尾的字符串,你应该使用类似 memcpy
或 strncpy
的东西(具有适当的长度)而不是 sprintf
,因为 sprintf
将在字符串末尾插入一个零字节。
关于C UNIX write() 函数插入奇怪的字符而不是空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19695798/