linux下C 大家帮我看看代码错哪里了 为什么结构体里的内容不能写到文件中呢

liyuzhu_1984 2008-04-28 01:59:23

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>



struct syster
{
char SysID[5];
char SysName[19];
char SubSysID[19];
char SubSysName[22];
int NodeID;
char NodeUpTime[30];
char NodeDescr[20];
}sys={"k1","Host","009","HostMonitor",2,"2005-04-01","node"};

char buf[100];

int WriteStruFile(char *ptrFileName, struct syster *ptrStr)
{
int fd;
int length;
int res;

memset(buf,0,sizeof(buf));
sprintf(buf,"[SysID]=%s\n",ptrStr->SysID);
printf("%s\n",buf);
if(fd = open(ptrFileName,O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE) == -1)
{
printf("open file failed!!");
return -1;
}
length = strlen(buf);
if ((res = write(fd, buf, length)) != length)
{
printf("Error writing to the file.\n");
exit(1);
}
close(fd);
}

int main()
{
WriteStruFile("/root/changye/wwww/SysTable",&sys);

return 0;
}


...全文
206 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
123ppmove 2008-04-28
  • 打赏
  • 举报
回复
运算符优先级问题啊;
liyuzhu_1984 2008-04-28
  • 打赏
  • 举报
回复
4楼正解 是我疏忽了 结贴了哈
hanb99 2008-04-28
  • 打赏
  • 举报
回复
fd的0是==的值,I SEE 了
hanb99 2008-04-28
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 hij333 的回复:]
if((fd = open(ptrFileName,O_WRONLY ¦ O_CREAT ¦ O_TRUNC, S_IREAD ¦ S_IWRITE))== -1)
{
printf("open file failed!!");
return -1;
}


上边的fd应该加上括号
[/Quote]
呵呵,高人!!!
linuxsir2007 2008-04-28
  • 打赏
  • 举报
回复

Node n;
.....

FILE* fp;
fp=fopen("1.dat","wb");
if(fp!=NULL)
{
fwrite(&n,sizeof(Node),1,fp);

}
fclose(fp);
hanb99 2008-04-28
  • 打赏
  • 举报
回复
而且如果有if的时候fd的值为0,会在屏幕上输出两次[SysID]=k1
如果去掉if,fd的值为3,只在屏幕上输出一次[SysID]=k1
我想会不会是因为fd的值为0所以程序把它当做标准输出,直接写到屏幕上了,没有写进文件,但它为什么会是0呢
hij333 2008-04-28
  • 打赏
  • 举报
回复
if((fd = open(ptrFileName,O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE) )== -1)
{
printf("open file failed!!");
return -1;
}


上边的fd应该加上括号
hanb99 2008-04-28
  • 打赏
  • 举报
回复
不知道,太怪了
如果写成这样就可以保存了
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

struct syster
{
char SysID[5];
char SysName[19];
char SubSysID[19];
char SubSysName[22];
int NodeID;
char NodeUpTime[30];
char NodeDescr[20];
}sys={"k1","Host","009","HostMonitor",2,"2005-04-01","node"};

char buf[100];

int WriteStruFile(char *ptrFileName, struct syster *ptrStr)
{
int fd;
int length;
int res;

memset(buf,0,sizeof(buf));
sprintf(buf,"[SysID]=%s\n",ptrStr->SysID);
printf("%s\n",buf);
fd = open(ptrFileName,O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE);

length = strlen(buf);
res = write(fd, buf, length);
close(fd);

}

int main()
{
WriteStruFile("/home/whf/aaa",&sys);//这个文件名是我自己的


return 0;
}

真怪,把所有的if去掉,OK
不明白
liyuzhu_1984 2008-04-28
  • 打赏
  • 举报
回复
存在
Wolf0403 2008-04-28
  • 打赏
  • 举报
回复
/root/changye/wwww

这些目录都存在么?

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧