#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int OpenToRW(char *filename);
int OpenToRW(char *filename)
{
int fd;
char str[30];
char stw[50];
int num;
char ch;
int temp = 0;
fd = open(filename, O_CREAT|O_RDWR, 0777);/*文件存在就打开,不存在就创建*/
if(fd == -1){
perror("Open File Failed!\n");
return 2;
}
while((num = read(fd, str, 29)) != 0){
str[num] = '\0'; //防止读出乱码
printf("%s", str);
}
printf("Input YOUR write:(<50)\n");
getchar(); //屏蔽掉上一个回车,很重要
while((ch = getchar()) != '#'){//接受字符遇到‘#’号结束
stw[temp++] = ch;
}
stw[temp] = '\0';
num = write(fd, stw, strlen(stw));//写入文件
if(num == -1){
printf("Write ERROR!\n");
return 3;
}
close(fd);
return 0;
}
int main(int argc, char *argv[])
{
int flag;
char filename[20];
printf("Input The filename you want to RW:\n");
scanf("%s", filename);
flag = OpenToRW(filename);
printf("OpenToWR:flag = %d\n", flag);
return 0;
}
|