begin linux programming

Recently,i begin to learn programming in linux , so i choose the book with the name of <<Begin linux programming>> as my first book of exploiting programming under linux . here , i will list some of the basic operations under linux to let you get involved in linux as soon as possible. also , the sequence of my blogging will begin with files.

In this chapter , you will know how to manipulate the files and the directories , you will learn how to open , read , write ,close them, and also the property of the file you are interested , lastly, we will take a close look at how to scan the directories under linux.

first of all, i just want to show you some basic function used in linux to manipulate fhe file.(i just wish you know that almost everything in linux is a file , so you can use the same way to manipulate the one you want):

int open(const char * path , int oflags);
int open(const char * path , int oflags , mode_t mode);



in simple terms , the open function establishes an access path to a file or device which is lead by path, and the oflags take the parameter of "R_RDONLY , O_WRONLY , O_RDWR , O_APPEND , O_TRUNC , O_CREAT , O_EXCL" as for the meaning of each parameter , i do suggest you look for the meaning  yourself by using the command of " man 2 open " under the terminals. by the way ,<fcntl.h> , <sys/types.h> <sys/stat.h> must be included ( strcitly speaking , there is no need including <sys/..> but the may be necessary on some UNIX system.


size_t read(int fildes , void * buffer , size_t nbytes);
size_t write(int fildes , const void * buf , size_t nbytes);



the read() and write() function are similar , so we just need to specify one , take the read() function as an example , the fildes it an nonnegaticve integer with the  type of int which is returned by open() function, and the buf refers to the buffer which will contain the content you read from the file , nbytes means the number you want to read from the file in bytes , last the return value means the real number of bytes you read from the file. don't forget the <unistd.h> when you want to use it , similar to write() function.

int close(int fildes);


close the file you have open with the parameter of fildes you get from open() function.

NOTE: never use a parameter with the name of " write , read , close , or something else " for that you will meet the error like this
"called object is not a function " if you insist on.

come with an example :




next i want to show you some other system calls which can be used to manipulate the file and also get the detailed property of the file

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


the fildes is determined by the fildes and the offset parameter is used to specify the position , and the whence parameter specifies how the offset is used , whence can be one of the following :
SEEK_SET   :  offset is an absolute position
SEEK_CUR   :  offset is relative to the current position
SEEK_END   :  offset is relatice to the end of the file

and the return value is measured in bytes from the beginning of the file that the file pointer is set to or -1ib failure, remember the off_t type is determined in <sys/types.h>

the most useful function about the file manipulation is as follows:

int fstat(int fildes , struct stat * buf)
int stat(const char * path , struct stat * buf)
int lstat(const char * path , struct stat * buf)


those functions can store the status information in a struct stat structure ,and you can see it below:


 struct stat  
    {  
      
        dev_t       st_dev;     /* ID of device containing file -文件所在设备的ID*/  
      
        ino_t       st_ino;     /* inode number -inode节点号*/  
      
        mode_t      st_mode;    /* protection -保护模式?*/  
      
        nlink_t     st_nlink;   /* number of hard links -链向此文件的连接数(硬连接)*/  
      
        uid_t       st_uid;     /* user ID of owner -user id*/  
      
        gid_t       st_gid;     /* group ID of owner - group id*/  
      
        dev_t       st_rdev;    /* device ID (if special file) -设备号,针对设备文件*/  
      
        off_t       st_size;    /* total size, in bytes -文件大小,字节为单位*/  
      
        blksize_t   st_blksize; /* blocksize for filesystem I/O -系统块的大小*/  
      
        blkcnt_t    st_blocks;  /* number of blocks allocated -文件所占块数*/  
      
        time_t      st_atime;   /* time of last access -最近存取时间*/  
      
        time_t      st_mtime;   /* time of last modification -最近修改时间*/  
      
        time_t      st_ctime;   /* time of last status change - */  
      
    };  






and you can see the result of this example to find the useful function stat() function:

suilingxi@ubuntu:~$ ./dir
a regular file
the time of last access :Fri Jan 31 18:04:00 2014

the time of last modification to contents : Wed Jan 22 17:31:35 2014

the number of hard links to the file : 1
suilingxi@ubuntu:~$

now  , let  begin with some other manipulation about the file


int unlink(const char * path);

int link(const  char * path1 , const char *path2);

int symlink(const char * path1 , const char * path2);


now show you an example:


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

int main(){
	/* establish the link toward the file block*/
	char path1[]="/home/suilingxi/test";
	char path2[]="/home/suilingxi/test2";
	char path3[]="/home/suilingxi/syslink";
	if(link(path1,path2)==0){
		printf("link ok\n");
	}

	/*read the content from the file test2*/
	int fildes=open(path2,O_RDONLY);
	if(fildes==-1){
		printf("open file test2 error\n");
		exit(0);
	}
	char buffer[100];
	memset(buffer,0,100);
	int readed=0;
	while((readed=read(fildes,buffer,100))>0){
		printf("the hard link content : %s\n",buffer);
	}

	/*establish the syslink toward the file test*/
	if(symlink(path1,path3)==0){
		printf("create soft link ok \n");
	}

	/*read the content from the soft link syslink*/
	int value=open(path3,O_RDONLY);
	if(value==-1){
		printf("read soft file symlink error\n");
		exit(0);
	}
	char buf[100];
	memset(buf,0,100);
	int r=0;
	while((r=read(value,buf,100))>0){
		printf("soft link content : %s\n",buf);
	}
	if(unlink(path2)==0){
		printf("delete hard link ok\n");
	}

	if(unlink(path3)==0){
		printf("delete soft link ok\n");
	}
return 0;
}



last i met some problems the time when i try scanning the directory , first i will display some basic function and explain them ,then i will come up with some examples i program also the example which written in the book , and compare them so as you can know the difference and make deep understanding into scanning directory:

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

int mkdir(const char * path, mode_t mode);

#include <unistd.h>

int rmdir(const char * path);
int chdir(const char * path);
char * getcwd(char * buf,size_t size);

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

DIR * opendir(const char * name);
struct dirent * readdir(DIR * dirp);
long int telldir(DIR * dirp);
void seekdir(DIR * dirp, long int loc);
int closedir(DIR * dirp);

and i do believe you will use the function fstat(), stat(),lstat() from <unistd.h> <sys/stat.h> <sys/types.h> to get the detailed properity of the direcitory of document you receive from opendir() and readdir() function , so as to judge the target wether a document or a directory.last i want to expalin one function which is very very very important in scanning the directory -------readdir()

struct dirent * readdir(DIR * dirp);

NOTE:
       1,successive calls to readdir return further directory entries , on error and at the end of the directory , readdir returns NULL .
       2,readdir() scanning isn't guaranteed to list all the files in a direcoty if there are other processes creating and deleting files in the         directory at the same time.
       3,to determine further details of a file in a directory , you need to amke a call to stat() fstat() lstat() function.

now show you the examples:


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

int deep(char * path,int tab);
int main(){
	char path[]="/home/suilingxi/dir";
	deep(path,0);
return 0;
}


int deep(char  path[] , int tab){
    DIR * d;
	struct dirent * dir;
	struct stat * s;
	/*must allocate the memory , if not , then you will meet the problem like"receive signal SIGSEGV and terminate the process "*/
	s=(struct stat *)malloc(sizeof(struct stat));
	d=opendir(path);
	if(d==NULL){
		printf("open dir error\n");
		exit(0);
	}

	/*set the path as the current path8*/
	if(chdir(path)==0){
	}else{
		printf("change dir error\n");
		exit(0);
	}
	/*read the dir from the path*/
	while((dir=readdir(d)) != NULL){
		if(stat(dir->d_name,s)==0){
		}else{
			printf("get prosperity error\n");
			exit(0);
		}

		if(S_ISDIR(s->st_mode)){
		   if(strcmp(dir->d_name,".")==0){
				printf("%*s.\n",tab,"");
				continue;
			}
		   if(strcmp(dir->d_name,"..")==0){
				printf("%*s..\n",tab,"");
				continue;
			}
			printf("%*s%s\n",tab,"",dir->d_name);
			deep(dir->d_name,tab+6);
		}else{
			printf("%*s%s\n",tab,"",dir->d_name);
		}
	}
	chdir("..");
	closedir(d);
return 0;
}


remember you must allocate the memory before called lstat() fucntion , and you can see the reason from stackoverflow:

2 down vote accepted

From what I can tell, the error is being caused by your failure to initialize the this_lstat that gets passed as the second parameter to lstat.

The error string "Bad address" corresponds to the error code EFAULT, which comes from passing an invalid pointer to a system call. So, either the path name being passed to lstat doesn't point to a valid null-terminated string in readable memory, or the struct stat being passed as the second parameter doesn't point to valid writable memory.

You seem to be passing an unitialized pointer, which is almost certainly pointing to invalid memory. Valgrind doesn't complain because up until the system call, you haven't done anything wrong—only when the kernel tries to access the memory does it realize its invalid.

To fix this, either allocate memory for the struct stat with malloc, or just pass a pointer to a variable on the stack instead of using a pointer:

struct stat this_lstat;
lstat(..., &this_lstat);


then i show you another example , in this exmaple you needn't allocate the memory but still can run:

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

void printdir(char * dir , int depth){
	DIR * dp;
	struct dirent * entry;
	struct stat statbuf;

	if((dp=opendir(dir))==NULL){
		fprintf(stderr,"cannot open directory : %s\n",dir);
		return;
	}
	chdir(dir);

	while((entry=readdir(dp)) != NULL){
		lstat(entry->d_name,&statbuf);
		if(S_ISDIR(statbuf.st_mode)){
			if(strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)
				continue;
			printf("%*s%s/\n",depth,"",entry->d_name);
			printdir(entry->d_name,depth+4);
		}else
			printf("%*s%s\n",depth,"",entry->d_name);
	}
	chdir("..");
	closedir(dp);
}

int main(int argc , char * argv[]){
	char * topdir=".";
/*	if(argc>2)*/
		topdir=argv[1];
	
	printf("Directory scan of %s\n",topdir);
	printdir(topdir,0);
	printf("done\n");
	return 0;
}

i am so sorry  that i don't know the reason why like this , and if you know , please contact me, appreciate.

数据治理是确保数据准确性、可靠性、安全性、可用性和完整性的体系和框架。它定义了组织内部如何使用、存储、保护和共享数据的规则和流程。数据治理的重要性随着数字化转型的加速而日益凸显,它能够提高决策效率、增强业务竞争力、降低风险,并促进业务创新。有效的数据治理体系可以确保数据在采集、存储、处理、共享和保护等环节的合规性和有效性。 数据质量管理是数据治理中的关键环节,它涉及数据质量评估、数据清洗、标准化和监控。高质量的数据能够提升业务决策的准确性,优化业务流程,并挖掘潜在的商业价值。随着大数据和人工智能技术的发展,数据质量管理在确保数据准确性和可靠性方面的作用愈发重要。企业需要建立完善的数据质量管理和校验机制,并通过数据清洗和标准化提高数据质量。 数据安全与隐私保护是数据治理中的另一个重要领域。随着数据量的快速增长和互联网技术的迅速发展,数据安全与隐私保护面临前所未有的挑战。企业需要加强数据安全与隐私保护的法律法规和技术手段,采用数据加密、脱敏和备份恢复等技术手段,以及加强培训和教育,提高安全意识和技能水平。 数据流程管理与监控是确保数据质量、提高数据利用率、保护数据安全的重要环节。有效的数据流程管理可以确保数据流程的合规性和高效性,而实时监控则有助于及时发现并解决潜在问题。企业需要设计合理的数据流程架构,制定详细的数据管理流程规范,并运用数据审计和可视化技术手段进行监控。 数据资产管理是将数据视为组织的重要资产,通过有效的管理和利用,为组织带来经济价值。数据资产管理涵盖数据的整个生命周期,包括数据的创建、存储、处理、共享、使用和保护。它面临的挑战包括数据量的快速增长、数据类型的多样化和数据更新的迅速性。组织需要建立完善的数据管理体系,提高数据处理和分析能力,以应对这些挑战。同时,数据资产的分类与评估、共享与使用规范也是数据资产管理的重要组成部分,需要制定合理的标准和规范,确保数据共享的安全性和隐私保护,以及建立合理的利益分配和权益保障机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值