simple_open.c:
#include<stdlib.h> /*for the exit call*/
#include<fcntl.h>
#include<stdio.h>
char *workfile="junk";
int main(void)
{
int filedes;
/*open using O_RDWR from <fcntl.h>*/
/*file to be opened for read/write*/
if((filedes=open(workfile,O_RDWR|O_CREAT,0644))==-1)
{
printf("Could n''t open %sn",workfile);
exit(1); /*error so exit*/
}
printf("successfully");
exit(0);
/*call open successfully*/
}
simple_read.c:
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#define BUFSIZE 512
int main(void)
{
char buffer[BUFSIZE];
int filedes;
ssize_t nread;
long total=0;
char filename[25];
printf("Please input the filename you want to count:");
scanf("%s",filename);
/*open "anotherfile" read only*/
if((filedes=open(filename,O_RDONLY))==-1)
{
printf("error in opening %sn",filename);
exit(1);
}
while((nread=read(filedes,buffer,BUFSIZE))>0)
{
total =nread;/*increment total*/
}
printf("total chars in %s :%ldn",filename,total);
exit(0);
}
本文出自 “C与Linux学习” 博客,请务必保留此出处http://jiangfeng.blog.51cto.com/1593252/511075
|