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终端配置并测试