1. 程式人生 > >linux網路程式設計學習筆記(一)

linux網路程式設計學習筆記(一)

目錄

1. 獲取系統呼叫錯誤資訊:errno   strerror()     perror();

他跟c語言中的fopen()有什麼區別呢? 

他也呼叫的是這個open();

2.常規檔案操作之建立、讀、寫

   1.檔案建立

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

int main(int argc,char *argv[])
{
	int fd = creat(argv[1],S_IRUSR|S_IWUSR|S_IWGRP|S_IROTH);//等價於下面
	//int fd = creat(argv[1],0664);
	if(-1 == fd)
	{
		perror("creat");//引號內容原樣輸出,後面緊跟出錯資訊;
		return -1;
	}
	printf("creat %s ok\n",argv[1]);
	return 0;
}

執行結果:

如何建立多個檔案呢?

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

int main(int argc,char *argv[])
{
	int fd = -1;
	int i = 1;//引數從下表為1開始
	while(argv[i]!=NULL)
	{
		fd = creat(argv[i],S_IRUSR|S_IWUSR|S_IWGRP|S_IROTH);//等價於下面
		//int fd = creat(argv[1],0664);
		if(-1 == fd)
	{
		perror("creat");//引號內容原樣輸出,後面緊跟出錯資訊;
		return -1;
	}
	printf("creat %s ok\n",argv[i]);
	}
	return 0;
}

執行結果:

2.開啟檔案:

標頭檔案:

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

引數   flag:O_RDONLY      O_WRONLY   O_RDWR

引數  mode:O_TRUN:開啟檔案時清空檔案         O_CREAT:建立檔案                  

巨集:O_APPEND:在檔案末尾追加

chmod o-r 檔名   意思:去掉其他使用者的讀許可權(-是去掉的意思)

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

int main(int argc,char *argv[])
{
	int fd = -1;
        //引數一:指定要開啟的檔案
        //開啟檔案做什麼
        //O_RDONLY   :只讀開啟檔案,不能寫
        //O_WRONLY   :只xxie寫開啟檔案,不能ddu讀
        //O_RDWR     :讀寫開啟檔案
        fd = creat(argv[1],O_RDONLY);//等價於下面
           if(-1 == fd)
	{
                perror("open");//引號內容原樣輸出,後面緊跟出錯資訊;
		return -1;
	}
        printf("open %s ok\n",argv[1]);
	}
	return 0;
}

測試結果:網上說檔案沒有是不會自動建立的,這點和c語言不同

                  但在unban下是可以的,我也不知道為啥!!

新增巨集的方式: int fd = open(argv[1],O_ONLY|O_CREAT)   用 | 的方式,如果檔案不存在,建立,如果存在,就開啟

3.寫檔案:write

fd:檔案描述符     buf:寫入資料的地址      count: 寫入的資料長度

ssize_t:實際寫入位元組數

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>

int main(int argc,char *argv[])
{
	int fd = -1;
        //O_APPEND:每次寫入資料時,都將資料寫在檔案末尾
		fd = open(argv[1],O_WRONLY|O_CREAT|O_APPEND,0664);
        if(-1 == fd)
		{
			perror("open");//引號內容原樣輸出,後面緊跟出錯資訊;
		    return -1;
		}
		printf("open %s ok\n",argv[1]);
		
		char cabuf[100] = {'\0'};
		ssize_t ret = -1;//ssize_t:整數
		while(1)
		{
			printf("please input data:\n");
			memset(cabuf,'\0',sizeof(cabuf));//每次用陣列時都需要清空一下
			scanf("%s",cabuf)//不安全,輸入字串不能有空格;容易越界
			if(0 == strcmp("exit",cabuf))
			{
				break;
			}
			ret = write(fd,cabuf,strlen(cabuf));
			if(0 == ret)
			{
				perror("write");
				break;
			}
		}
		close(fd);//為什麼一定要關閉檔案?   
		return 0;
}

//若開啟檔案成功,我那件的讀寫位置預設在檔案首位

//讀寫位置隨讀寫操作自動往後偏移

 4.讀檔案:

引數同寫相同     錯誤返回-1

讀取大資料到資料夾:

#include <stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

int main(int argc, char *argv[])
{
        double data[9999]={0};
        printf("start!\n");
        int fd = open(argv[1],O_RDWR|O_CREAT);
        ssize_t ret = 0;
        int iwrite = 0;
        int ileft = sizeof(data);
        printf("iletf = %d",ileft);
        while(ileft)
        {
                if(ileft>4096)
                {
                        ret = write(fd,(char*)data+iwrite,4096);
                }
                else
{
                        ret = write(fd,(char *)data+iwrite,ileft);
                }
                if(0 == ret)
                {
                        perror("write");
                        break;
                }
                iwrite += ret;
                ileft -=ret;
        }
        close(fd);
        return 0;
}

3.資料夾操作:

 1.建立目錄:

命令 :mkdir   :

 使用mkdir函式來建立資料夾:

 mode:許可權

判斷資料夾是否存在?access()函式: access, faccessat - check user's permissions for a file(檢查使用者對檔案有什麼操作許可權)

      The mode specifies the accessibility check(s) to be performed,  and  is        either the value F_OK, or a mask consisting of the bitwise OR of one or        more of R_OK, W_OK, and X_OK.  F_OK tests  for  the  existence  of  the        file(檢查檔案是否存在).   R_OK,  W_OK,  and  X_OK test whether the file exists and grants        read, write, and execute permissions, respectively.

返回值:針對F_OK:返回0 ,失敗返回  :-1;

#include <stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

int main(int argc, char *argv[])
{
        int ret = -1;
        int i = 1;
        printf("argc = %d\n",argc);
        for(;i<argc;i++)
        {
                ret = access(argv[i],F_OK);
                if(0 == ret)
                {
                        printf("%s existed\n",argv[i]);
                }
                ret = mkdir(argv[i],0777);
                if(-1 == ret )
                {
                        perror("mkdir");
                }
        }
    printf("end!\n");
        return 0;
}

刪除資料夾:rm 檔名   -rf

2.重新設定檔案讀寫檔案位置:

NAME        lseek - reposition read/write file offset(重新定義檔案讀寫的偏移量)

SYNOPSIS        #include <sys/types.h>        #include <unistd.h>

       off_t lseek(int fd, off_t offset, int whence);        

       whence: 參照物:取值  :檔案首部,檔案末尾,當前位置

       offset :偏移量    

       SEEK_SET(檔案首位置)               The file offset is set to offset bytes.

       SEEK_CUR(當前位置)               The  file  offset  is  set  to  its current location plus offset               bytes.

       SEEK_END(檔案末尾)               The file offset is set to the  size  of  the  file  plus  offset               bytes.

    返回值:RETURN VALUE    成功:返回新的位置距離檔案首位置的位元組數;失敗:返回-1;

       Upon successful completion, lseek() returns the resulting offset  loca‐        tion  as  measured  in bytes from the beginning of the file.  On error,        the value (off_t) -1 is returned and  errno  is  set  to  indicate  the        error.

#include <stdio.h>
#include <sys/types.h>      
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int fd = open(argv[1],O_RDONLY);
	off_t offset = -1;
	offset = lseek(fd,0,SEEK_END);
	if((off_t)-1 == offset)
	{
		perror("lseek");
		return -1;
	}
	printf("file size:%ld\n",offset);
	close(fd);
	return 0;
}

執行結果:

3.開啟資料夾:

NAME        opendir, fdopendir - open a directory

SYNOPSIS        #include <sys/types.h>        #include <dirent.h>

       DIR *opendir(const char *name);        DIR *fdopendir(int fd);

      RETURN VALUE(返回值)成功:返回指向檔案的指標    失敗:返回:NULL        The opendir() and fdopendir() functions return a pointer to the  direc‐        tory  stream.   On  error, NULL is returned, and errno is set appropri‐        ately.

#include <stdio.h>
#include<string.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
	DIR *pDir = opendir(argv[1]);
	if(NULL = pDir)
	{
		perror("opendir");
		return -1;
	}
	printf("open dir %s ok \n",argv[1]);
	closedir(pDir);
	
	return 0;
}

4.檢視資料夾裡面的資訊:

NAME        readdir - read a directory

SYNOPSIS        #include <dirent.h>

       struct dirent *readdir(DIR *dirp);

 struct dirent {                ino_t          d_ino;       /* Inode number */                off_t          d_off;       /* Not an offset; see below */                unsigned short d_reclen;    /* Length of this record */                unsigned char  d_type;      /* Type of file; not supported  by all filesystem types */ (並不是支援所有的檔案型別)                char           d_name[256]; /* Null-terminated filename */            };

返回值:成功:返回結構體地址   失敗:返回NULL;

#include<string.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
        DIR *pDir = opendir(argv[1]);
        if(NULL == pDir)
        {
                perror("opendir");
                return -1;
        }
        printf("open dir %s ok \n",argv[1]);

        struct dirent *pDirent = NULL;
        while(1)
        {
                pDirent = readdir(pDir);//»ñµÃÆäÖÐijһ¸öÎļþµÄÐÅÏ¢
                if(NULL == pDirent)
                {
                        break;
                }
                printf("filename :%s\t",pDirent->d_name);
        }
        printf("\n");
        closedir(pDir);

        return 0;
}

5.建立多級目錄:

NAME        strchr, strrchr, strchrnul - locate character in string(找字串中是否包含某個字元)

SYNOPSIS        #include <string.h>

       char *strchr(const char *s, int c);

       char *strrchr(const char *s, int c);

#include <stdio.h>
#include<string.h>
#include<sys/types.h>
#include<dirent.h>
#include<unistd.h>

// ./mkdir_duoji  aa/bb/cc/dd
int main(int argc, char *argv[])
{
        char capath[256] = {'\0'};
        char *p = argv[1];
        while(1)
        {
                p = strchr(p,'/');
                if(NULL!=p)
                {
                        strncpy(capath,argv[1],p-argv[1]);//¿½±´p-argv[1]¸öµÄ×Ö½Ú
                        if(-1 == access(capath,F_OK))
                        {
                                mkdir(capath,0777);
                        }
                }
                else
                {
                        strcpy(capath,argv[1]);
                        if(-1 == access(capath,F_OK))
                        {
                                mkdir(capath,0777);
                        }
                        break;
                }
                p++;
        }
        return 0;
}