C++基于LINUX的文件操作
引言
討論套接字的過程討論突然提及文件也許有些奇怪。但對于LINUX而言,socket操作和文件操作沒有區(qū)別,Linux一切皆為文件,因此文件的IO函數(shù)也是socket的IO函數(shù),本文旨在給讀者擴充知識,不必記住所謂的代碼
底層文件訪問和文件描述符
- 底層:與標準無關(guān)底層提供的函數(shù)
文件描述符:系統(tǒng)分配給文件或者套接字的整數(shù),windows被稱為句柄,用來描述一種時間類型或者事務。
打開文件
#include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int open(const char* path, int flag)
關(guān)閉文件
#include<unistd.h> int close(int fd);
fd->需要關(guān)閉的文件或者套接字的文件描述符
將數(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的文件操作的詳細內(nèi)容,更多關(guān)于C++ LINUX文件操作的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C/C++編譯報錯printf was not declared in 
這篇文章主要介紹了C/C++編譯報錯printf was not declared in this scope問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
c++實現(xiàn)逐行讀取配置文件寫入內(nèi)存的示例
這篇文章主要介紹了c++實現(xiàn)逐行讀取配置文件寫入內(nèi)存的示例,需要的朋友可以參考下2014-05-05
C++11中的智能指針shared_ptr、weak_ptr源碼解析
本文是基于gcc-4.9.0的源代碼進行分析,shared_ptr和weak_ptr是C++11才加入標準的,僅對C++智能指針shared_ptr、weak_ptr源碼進行解析,需要讀者有一定的C++基礎(chǔ)并且對智能指針有所了解2021-09-09

