Linux 2.1:文件系统与操作 学习心得

1.代码规范:

(1)上学期学习c语言时,我习惯将花括号打成独立的两行,现在老师要求代码要规范,对花括号的位置有要求,如:

int main{

}

(2)对注释也有要求,如:

if a==2{

}//of if
或
for(i=1;i<2;i++){

}//of for

(3)定义变量规范性:我以前定义变量很简洁,如int a,float b等等,现更改习惯,定义变量为:

int tempA;
int tempB;
//等等

案例1: 使用open函数打开或创建一个文件,将文件清空,使用write函数在文件中写入数据,并使用read函数将数据读取并打印。

源代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(){
	int tempFd = 0;
	char tempFileName[20] = "test.txt";
	//Step 1. open the file.
	tempFd = open(tempFileName, O_RDWR|O_EXCL|O_TRUNC, S_IRWXG);
	if(tempFd == -1){
		perror("file open error.\n");
		exit(-1);
	}//of if
	//Step 2. write the data.
	int tempLen = 0;
	char tempBuf[100] = {0};
	scanf("%s", tempBuf);
	tempLen = strlen(tempBuf);
	write(tempFd, tempBuf, tempLen);
	close(tempFd);
	//Step 3. read the file
	tempFd = open(tempFileName, O_RDONLY);
	if(tempFd == -1){
		perror("file open error.\n");
		exit(-1);
	}//of if
	off_t tempFileSize = 0;
	tempFileSize = lseek(tempFd, 0, SEEK_END);
	lseek(tempFd, 0, SEEK_SET);
	while(lseek(tempFd, 0, SEEK_CUR)!= tempFileSize){
		read(tempFd, tempBuf, 1024);
		printf("%s\n", tempBuf);
	}//of while
	close(tempFd);
	return 0;
}//of main

涉及知识点:

一,open函数:

#include <fcntl.h>
int open(const char *pathname, int flags[, mode_t mode);

二,read函数:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

三,write函数:

#include <unistd.h>
ssize_t write(int fd, void *buf, size_t count);

四,lseek函数:

#include <unistd.h>
ssize_t write(int fd, off_t offset, int whence);

五,close函数:

#include <unistd.h>
int close(int fd);

在linux终端配置并测试

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值