システム呼び出しファイルの読み書き操作

2574 ワード

ファイルからデータを読み込む
1コード
#include
#include
#include
#include
#include

int main(void)
{
    int fd = -1,i;
    ssize_t size =-1;
    char buf[10];   
    char filename[] = "/root/test.txt"; //      

    fd = open(filename,O_RDONLY); //        
    if(-1==fd)
    {   
            printf("Open file %s failuer,fd:%d
",filename,fd); return -1; } else printf("Open file %s success,fd:%d
",filename,fd); // , while(size) { // ,10 10 , size = read(fd,buf,10); if(-1==size) { close(fd); printf("Read file %s error occurs
",filename); return -1; }else{ if(size>0) { printf("read %d bytes:",size); printf("\""); for(i =0;i

2運転
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
Open file /root/test.txt success,fd:3
read 10 bytes:"fhdjslfgdh"
read 10 bytes:"jdskfjsdhj"
read 10 bytes:"gfdlfgdfg;"
read 10 bytes:"dfgflk
fsd"
read 10 bytes:"klfjsfjdlf"
read 10 bytes:"jdk
nfjsdk"
read 1 bytes:"
"
reach the end of file
[root@localhost test]# cat /root/test.txt
fhdjslfgdhjdskfjsdhjgfdlfgdfg;dfgflk
fsdklfjsfjdlfjdk
nfjsdk

ファイルへのデータの書き込み
1コード
#include
#include
#include
#include
#include
#include

int main(void)
{
    int fd = -1,i;
    ssize_t size =-1;
    int input =0;
    
    char buf[] = "boys and girls
hi,children!"; char filename[] = "test.txt"; fd = open(filename,O_RDWR|O_APPEND); if(-1==fd) { printf("Open file %s faliluer
",filename ); }else{ printf("Open file %s success
,=",filename ); } size = write(fd,buf,strlen(buf)); printf("write %d bytes to file %s
",size,filename); close(fd); return 0; }

2運転
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# touch test.txt
[root@localhost test]# ./test
Open file test.txt success
,=write 28 bytes to file test.txt