C UNIX write() 函数插入奇怪的字符而不是空格

标签 c unix unix-timestamp stat

这是一项任务(不是我的,而是我正在帮助的人,如果这很重要的话),但应该编写一个模仿 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 中以空字符结尾的字符串,你应该使用类似 memcpystrncpy 的东西(具有适当的长度)而不是 sprintf,因为 sprintf 将在字符串末尾插入一个零字节。

关于C UNIX write() 函数插入奇怪的字符而不是空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19695798/

相关文章:

c - 警告 : passing argument 1 of 'pushPost' makes pointer from integer without a cast [-Wint-conversion] in my infix to postfix progam

c - 分配连续内存

swift - 从 Swift 读取 Unix 时间

c - pthread_atfork 锁定习语坏了?

c++ - 未定义的 C/C++ 符号作为运算符

c - 在 C 中通过引用传递不同于 C++?

regex - 用尾随 9 舍入数值

unix - 在UNIX中解析CSV文件,但也处理“”内的数据

sql-server - MSSQL bigint Unix Timestamp 到 Datetime 以毫秒为单位

json - epoch 快速将 json int(unix 时间戳)转换为可读日期