日期:2014-05-16  浏览次数:20779 次

文件写入读取小程序,希望各位大神帮忙修改一下~~~
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZ 20
#define RETURN_FAILURE 20
int rd();
int wr();
char buffer[SIZ] = "\0";
int nread = 0;
int fd;
int main(int argc, char **argv)
{
int rw;
if (argc < 2) {
fprintf(stderr, "illegal operation");
return(RETURN_FAILURE);
}
if (!strcmp("read", argv[1])) {
rw = 1; /* read mode */
printf("[read mode]\n");
}
else {
if (!strcmp("write", argv[1])) {
rw = 0; /* write mode */
printf("[write mode]\n");
}
}
switch (rw) {
case 0:
wr();
break;
case 1:
rd();
break;
default:
break;
}
return(0);
}
int rd()
{
if ((fd = open("text", O_RDONLY)) == -1) {
fprintf(stderr, "file open error\n");
return(RETURN_FAILURE);
}
while ((nread = read(fd, buffer, SIZ)) != 0) {
write(1, buffer, nread);
}
close(fd);
}
int wr()
{
while (nread < SIZ) {
buffer[nread++] = getc(stdin);
if (nread > SIZ)
printf("Buffer overrun");
}
if ((write(1, buffer, nread)) != nread)
write(2, "A write error has occurred\n", 27);
if ((fd = open("text", O_WRONLY)) == -1) {
fprintf(stderr, "file open error\n");
return(RETURN_FAILURE);
}
else
write(fd, buffer, SIZ);
close(fd);
}
现在这个代码是建立一个text文件,进行读写操作,第二次写入会把第一次写入的东西覆盖掉,我怎么修改这个代码可以不覆盖之前写入的东西呢?

------解决方案--------------------
if ((fd = open("text", O_WRONLY|O_APPEND)) == -1)
这样看看