linux網絡編程學習筆記(一)

目錄

1. 獲取系統調用錯誤信息:errno   strerror()     perror();

2.常規文件操作之創建、讀、寫

   1.文件創建

   2.打開文件:

   3.寫文件:write

   4.讀文件:

3.文件夾操作:

 1.創建目錄:

 2.重新設置文件讀寫文件位置:

 3.打開文件夾:

 4.查看文件夾裏面的信息:

 5.創建多級目錄:


 


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;
}


 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章