文件读写问题(在线等待)

shiyanhld 2003-09-07 09:19:29
用c++写一个cgi程序,是个简单的注册程序,我用一个文本data纪录登陆人的信息然后以一个record的结构写入,但是当我要写update的部分的时候问题出现了。新用户注册时文件data是以filedescriptor = open(datafileName,O_RDWR|O_APPEND);的语句打开的这样新的记录可以在最后添加,可是要更新信息的时候我该怎么打开,我尝试filedescriptor = open(datafileName, O_RDWR);这样打开,可是每当找到要更新的信息后我用write(filedescriptor, &myData, sizeof(datarecord));新入都是覆盖第一个用户的记录,好像指针不动,请问我该如何控制文件的位置,用什么函数,我的文件包含如下的库#include <iostream>
using namespace::std;
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/file.h>
...全文
34 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
shiyanhld 2003-09-09
  • 打赏
  • 举报
回复
lseek and fseek can be used to determine the position, but when I open a file using a certain method, if using APPEND , when I use write() to output the result, it will append the data at the end of the file. O_WRRD used, it will write data from the beginning of the file, no matter where you set your lseek or fseek, it has no meaning to write(), so I use pwrite() to solve this problem because this function can give the position to write as a argument. Thanks above, but no mark for anyone .
shiyanhld 2003-09-08
  • 打赏
  • 举报
回复
是不是O_RDWR|O_APPEND打开的时候写入都是写道文件末尾,而O_RDWR写入都是写道文件开头?有没有我自己可以控制写入位置的方式?
nirvana_ya 2003-09-08
  • 打赏
  • 举报
回复
我写过类似的程序,我是这样实现的.
1.按二进制读写文件.
2.每条记录定长.
3.以读写方式打开文件.
4.把写的信息转换到成二进制
3.用setp设置写入位置.
ianzy 2003-09-08
  • 打赏
  • 举报
回复
用 lseek, fseek 等函数定位, 然后再写数据。
yzlstone 2003-09-08
  • 打赏
  • 举报
回复
我也碰到过打开文件的类似问题。不过我对你的描述不是很清楚。
新用户注册时文件data是以filedescriptor = open(datafileName,O_RDWR|O_APPEND)语句打开的,新的记录可以在最后添加。
可是要更新信息的时候,你尝试用filedescriptor = open(datafileName, O_RDWR)打开,
为什么更新信息的时候再打开,不再用参量O_APPEND,显然不能追加。指针在文件头。
我建议:在更新信息之前,先关闭文件data,重新以filedescriptor = open(datafileName,O_RDWR|O_APPEND)语句打开,再用write(filedescriptor, &myData, sizeof(datarecord))写入。
如果不先关闭文件data,你等于两次打开同一个文件。
有何不妥,还请指教。
shiyanhld 2003-09-08
  • 打赏
  • 举报
回复
#include <fcntl.h>
哪里有这个库的介绍?
beijin 2003-09-08
  • 打赏
  • 举报
回复
up
shiyanhld 2003-09-08
  • 打赏
  • 举报
回复
up
shiyanhld 2003-09-08
  • 打赏
  • 举报
回复
upupup
shiyanhld 2003-09-08
  • 打赏
  • 举报
回复
up
oldfhp 2003-09-07
  • 打赏
  • 举报
回复
式不是应该把文件记录指向末尾。
zhuixe 2003-09-07
  • 打赏
  • 举报
回复
你说得也不清楚,多试试吧
shiyanhld 2003-09-07
  • 打赏
  • 举报
回复
up

24,853

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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