C++基于LINUX的文件操作
引言
討論套接字的過程討論突然提及文件也許有些奇怪。但對于LINUX而言,socket操作和文件操作沒有區(qū)別,Linux一切皆為文件,因此文件的IO函數(shù)也是socket的IO函數(shù),本文旨在給讀者擴充知識,不必記住所謂的代碼
底層文件訪問和文件描述符
- 底層:與標準無關底層提供的函數(shù)
文件描述符:系統(tǒng)分配給文件或者套接字的整數(shù),windows被稱為句柄,用來描述一種時間類型或者事務。
打開文件
#include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int open(const char* path, int flag)
關閉文件
#include<unistd.h> int close(int fd);
fd->需要關閉的文件或者套接字的文件描述符
將數(shù)據(jù)寫入文件
#include<unistd.h> ssize_t write(int fd, const void* buf, size_t nbytes);
fd顯示數(shù)據(jù)傳輸對象的文件描述符。
將數(shù)據(jù)寫入文件
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> void error_handling(char* message); int main(void) { int fd; char buf[]="Let's go!\n"; fd=open("data.txt", O_CREAT|O_WRONLY|O_TRUNC); if(fd==-1) error_handling("open() error!"); printf("file descriptor: %d \n", fd); if(write(fd, buf, sizeof(buf))==-1) error_handling("write() error!"); close(fd); return 0; } void error_handling(char* message) { fputs(message, stderr); fputc('\n', stderr); exit(1); } /* root@com:/home/swyoon/tcpip# gcc low_open.c -o lopen root@com:/home/swyoon/tcpip# ./lopen file descriptor: 3 root@com:/home/swyoon/tcpip# cat data.txt Let's go! root@com:/home/swyoon/tcpip# */
讀取文件中的數(shù)據(jù)
#include <unistd.h> ssize_t read(int fd, void* buf, size_t nbytes);
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #define BUF_SIZE 100 void error_handling(char* message); int main(void) { int fd; char buf[BUF_SIZE]; fd=open("data.txt", O_RDONLY); if( fd==-1) error_handling("open() error!"); printf("file descriptor: %d \n" , fd); if(read(fd, buf, sizeof(buf))==-1) error_handling("read() error!"); printf("file data: %s", buf); close(fd); return 0; } void error_handling(char* message) { fputs(message, stderr); fputc('\n', stderr); exit(1); } /* root@com:/home/swyoon/tcpip# gcc low_read.c -o lread root@com:/home/swyoon/tcpip# ./lread file descriptor: 3 file data: Let's go! root@com:/home/swyoon/tcpip# */
文件描述符與套接字
下面將同時創(chuàng)建文件和套接字,并用整數(shù)形態(tài)比較返回的文件描述符值。
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/socket.h> int main(void) { int fd1, fd2, fd3; fd1=socket(PF_INET, SOCK_STREAM, 0); fd2=open("test.dat", O_CREAT|O_WRONLY|O_TRUNC); fd3=socket(PF_INET, SOCK_DGRAM, 0); printf("file descriptor 1: %d\n", fd1); printf("file descriptor 2: %d\n", fd2); printf("file descriptor 3: %d\n", fd3); close(fd1); close(fd2); close(fd3); return 0; }
以上就是C++基于LINUX的文件操作的詳細內容,更多關于C++ LINUX文件操作的資料請關注腳本之家其它相關文章!
相關文章
詳解C語言中strcpy()函數(shù)與strncpy()函數(shù)的使用
這篇文章主要介紹了詳解C語言中strcpy()函數(shù)與strncpy()函數(shù)的使用,是C語言入門學習中的基礎知識,需要的朋友可以參考下2015-08-08