Linux系统编程
程序员文章站
2022-06-24 17:01:53
...
文末自带资料。
系统调用的文件操作:
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
typedef struct student
{
int sno;
char name[30];
struct student *next ;
}student ;
student * createStu()
{
student * head = NULL ;
student *pnew = NULL ;
char cmd ;
while(1)
{
printf("添加学生么? [y/n]\n") ;
cmd = getchar() ;
if('y' == cmd || 'Y' == cmd)
{
pnew = (student*)malloc(sizeof(student)) ;
printf("sno = ") ;
scanf("%d",&(pnew -> sno)) ;
while(getchar()!='\n') ;
printf("name = ") ;
scanf("%s",pnew -> name) ;
while(getchar()!='\n') ;
pnew -> next = head ;
head = pnew ;
}else
break ;
}
return head ;
}
void showStu(student*head)
{
if(NULL == head)
printf("NONE data of student\n") ;
student * p = head ;
while(p)
{
printf("student : sno = %d , name = %s\n",p->sno,p->name) ;
p = p -> next ;
}
}
student * freeStu(student *head)
{
student * p = NULL ;
while(head)
{
p = head ;
head = head -> next ;
free(p) ;
}
return head ;
}
int get_line(int fd , char *buf , int buf_max_len)
{
if(NULL == buf)
return -1 ;
int ret = 0;
int ret2 ;
char c ;
while(1)
{
ret2 = read(fd, &c , 1) ;
if(ret2 < 0)
{
perror("my read:\n") ;
break ;
}else if(ret2 == 0)
{
break ;
}
if('\n' == c || '\r' == c)
break ;
buf[ret] = c;
ret += ret2 ;
if(ret >= buf_max_len)
{
printf("data over the container's max len") ;
break ;
}
}
return ret ;
}
int main(int argc , char **argv)
{
student *head =NULL ;
/*head = createStu() ;
showStu(head) ;
int fw = open("./stu.txt",O_WRONLY|O_CREAT|O_TRUNC,0640) ;
if(fw < 0)
perror("creata stu.txt failed\n") ;
else
{
student *temp = head ;
char buf[sizeof(student)+1] = {0} ;
while(temp)
{
sprintf(buf , "%d %s\n",temp->sno , temp -> name) ;
if(write(fw , buf , strlen(buf)) != strlen(buf))
{
printf("write error %d %s\n",__LINE__ , __FILE__) ;
break ;
}
temp = temp -> next ;
}
}
close(fw) ;
head = freeStu(head) ;
if(NULL == head)
printf("free finished!\n");*/
printf("check file access\n") ;
int acc = access(argv[1],W_OK|R_OK) ;
if(acc == -1)
{
perror("access:") ;
}else
{
printf("[%s] writable and readable\n",argv[1]) ;
}
printf("============read file ============\n") ;
int fd = open("./stu.txt",O_RDONLY);
if(fd < 0)
{
perror("my open: \n") ;
}
int ret ;
char bufRe[1024] = {0};
student *p = NULL ;
while(1)
{
p = (student*)malloc(sizeof(student)) ;
p -> next = NULL ;
ret = get_line(fd, bufRe , sizeof(bufRe)) ;
if(ret <= 0)
break ;
sscanf(bufRe , "%d %s" , &(p->sno) ,p->name) ;
p -> next = head ;
head = p ;
}
showStu(head) ;
close(fd) ;
head = freeStu(head) ;
if(NULL == head)
printf("free finished!\n") ;
return 0 ;
}
下一篇: vue中使用typescript配置步骤
推荐阅读