gpt4 book ai didi

c - Unix 代码中的这个 C 可能有什么问题

转载 作者:太空宇宙 更新时间:2023-11-04 05:29:54 25 4
gpt4 key购买 nike

我对编写 C 代码还很陌生,我确信我在最基本的层面上有问题。我正在运行一个小代码来获取文件的属性,下面的这个函数返回这些属性。char *path 将包含类似“/home/etc/bin”的内容

/* copy the attributes into a character pointer */
unsigned char * copyAttributes (char *path)
{
struct stat buf;
stat (path, &buf);
int nMalloc = sizeof(dev_t) + sizeof(ino_t) + sizeof(mode_t)+ sizeof(nlink_t)+ sizeof(uid_t)+ sizeof(gid_t)+ sizeof(dev_t)+ sizeof(off_t)+ sizeof(blksize_t)+ sizeof(blkcnt_t)+ sizeof(time_t)+ sizeof(time_t)+ sizeof(time_t)+ 1;
char *pathForStatBuff = malloc(nMalloc);
printf("%d\n",nMalloc);
unsigned long base = 0;
memcpy(pathForStatBuff + base,&buf.st_dev,sizeof(dev_t));
base = base + sizeof(dev_t);
memcpy(pathForStatBuff + base,&buf.st_ino,sizeof(ino_t));
base = base + sizeof(ino_t);
memcpy(pathForStatBuff + base,&buf.st_mode,sizeof(mode_t));
base = base + sizeof(mode_t);
memcpy(pathForStatBuff + base,&buf.st_nlink,sizeof(nlink_t));
base = base + sizeof(nlink_t);
memcpy(pathForStatBuff + base,&buf.st_uid,sizeof(uid_t));
base = base + sizeof(uid_t);
memcpy(pathForStatBuff + base,&buf.st_gid,sizeof(gid_t));
base = base + sizeof(gid_t);
memcpy(pathForStatBuff + base,&buf.st_rdev,sizeof(dev_t));
base = base + sizeof(dev_t);
memcpy(pathForStatBuff + base,&buf.st_size,sizeof(off_t));
base = base + sizeof(off_t);
memcpy(pathForStatBuff + base,&buf.st_blksize,sizeof(blksize_t));
base = base + sizeof(blksize_t);
memcpy(pathForStatBuff + base,&buf.st_blocks,sizeof(blkcnt_t));
base = base + sizeof(blkcnt_t);
memcpy(pathForStatBuff + base,&buf.st_atime,sizeof(time_t));
base = base + sizeof(time_t);
memcpy(pathForStatBuff + base,&buf.st_mtime,sizeof(time_t));
base = base + sizeof(time_t);
memcpy(pathForStatBuff + base,&buf.st_ctime,sizeof(time_t));
base = base + sizeof(time_t);

printf("Printing pathForStatBuff = %s\n",pathForStatBuff);
return pathForStatBuff;
}

打印路径ForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p53打印 pathForStatBuff = p

这是我总是得到的输出,我似乎无法弄清楚我做错了什么。你们能指导我它可能是什么吗?谢谢。

最佳答案

您正在尝试将二进制数据用作字符串。在 C 中,字符串以零结尾,这意味着如果一个成员为零,那么当您将其复制到缓冲区中时,它将标记字符串的结尾。

如果您想将所有数据转换为字符串,您应该使用例如snprintf 改为:

char buffer[128];
snprintf(buffer, sizeof(buffer), "%d %d %d",
buf.st_dev, buf.st_ino, buf.st_mode);

请参阅 snprintf 的手册页有关该功能的更多信息。

(在我的示例中我只使用了结构的三个成员,添加所有你需要的。)

关于c - Unix 代码中的这个 C 可能有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9798752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com