文件IO的最常用的HelloWorld
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int fd;
int main(){
//创建文件
fd = open("file.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU | S_IRWXG | S_IRWXO); //777
if(fd < 0){
printf("BUG_OPEN\n");
exit(0);
}
//写入一些东西
char str[] = "Hello";
if(write(fd, str, strlen(str)) <= 0){
printf("BUG_WRITE\n");
exit(0);
}
//重置光标
if(lseek(fd, 0, SEEK_SET) < 0){
printf("BUG_SEEK\n");
exit(0);
}
//查看刚刚写入的东西
char buffer[6] = "12345";
int numReaded = read(fd, buffer, strlen(str));
if(numReaded == 0){
printf("EOS\n");
exit(0);
}else if(numReaded < 0){
printf("BUG_READ\n");
exit(0);
}
sleep(3); //等一会儿让文件读取
printf("%s\n", buffer);
//关闭文件
close(fd);
return 0;
}