题目:打开一个文件,若文件不存在,则创建文件并输入一传字符进文件。下次执行时,发现文件存在则输出文件内容
#include
#include
int main()
{
int fd;
char str[20]="",ch[20]="";
if((fd=open("example",O_CREAT|O_EXCL|O_RDWR,S_IRUSR|S_IWUSR))>0)
{
printf("input message:");
scanf("%s",str);
str[strlen(str)]='\0';
write(fd,str,strlen(str));
}
else
{
printf("file is exist!\n");
fd=open("example",O_RDWR);
read(fd,ch,20);
printf("%s\n",ch);
}
close(fd);
return 0;
}
对上边程序的改进(不用printf等,改用stdin,stdout):
#include
#include
#include
#include
#include
int main()
{
int fd,fp1,fp2;
int ret;
char str[20]="";
if((fd=open("example",O_CREAT|O_EXCL|O_RDWR,S_IRUSR|S_IWUSR))>0)
{
printf("input message:");
fp1=open("/dev/stdin",O_RDWR);
ret = read(fp1,str,20);
// str[ret-1]='\0';
str[strlen(str)-1]='\0';
write(fd,str,strlen(str));
close(fp1);
}
else
{
printf("file is exist!\n");
fd=open("example",O_RDWR);
fp2=open("/dev/stdout",O_RDWR);
read(fd,str,20);
write(fp2,str,strlen(str));
printf("\n");
}
close(fp2);
close(fd);
return 0;
}
阅读(594) | 评论(0) | 转发(0) |