memcpy然后是printf,调用stat(),写入缓冲区; [英] memcpy and then printf, calling stat(), writing in buffer;
本文介绍了memcpy然后是printf,调用stat(),写入缓冲区;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是包含项和我的功能:
here are includes and my function:
我正在尝试使用memcpy
在缓冲区中复制stbuf->st_mode
,并且在读回时,值不是我要复制的内容.
I'm trying to copy stbuf->st_mode
in buffer with memcpy
and when reading it back, value is not what I was trying to copy.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
void r1_getattr(char* pth, int cfd){
struct stat* stbuf = malloc(sizeof(stat));
int res = stat(pth, stbuf);
printf("(%3o)\n", (stbuf->st_mode)&0777);
char* wbuf = malloc(256);
memcpy(wbuf, &(stbuf->st_mode), sizeof(mode_t));
printf("(%3o)\n", (*(mode_t*)((char*)wbuf))&0777);
}
输出:(775)"和(21)"不应该相同吗?
outputs: "(775)" and "( 21)" shouldn't they be the same?
推荐答案
简单的键入错误:
替换
struct stat *stbuf = malloc(sizeof(stat));
使用
struct stat *stbuf = malloc(sizeof(struct stat));
当我们使用未初始化的内存时看到奇怪的结果总是很有趣:-)
Always funny to see the weird results we get when we use un-initialized memory :-)
这篇关于memcpy然后是printf,调用stat(),写入缓冲区;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文