- 引入
- 课程内容
- 代码错误
- 修改后可运行的版本:
- 成功运行
- 总结
引入Ubuntu20.04之前已经装好了,也一直在用,和服务器版本相同(
师傅们别打了)。博客也快两个月没水文章了,但是笔记都有在坚持做,只是没什么时间(bushi)搬运到博客和个人网站上。最近Python写多了,写C语言时分号老忘写…
温习下之前学过的C语言相关文件操作函数:
首先是简单介绍了下这门课程的重要性,接着回顾了Linux的一些相关知识。后面就是在Ubuntu下使用Codeblocks进行C编程了
代码错误代码主要功能是用open函数打开test.txt并将文件内容清空,用write函数将read函数读取到的数据打印出来,简单讲就是把输入的一行字符串输出到控制台并写入指定文件中
下面是老师提供的源代码,有几处错误:
- 24行的 int 应改为 if
- 31行的参数 Codeblocks 提示有误,应为 SEEK_CUR
#include修改后可运行的版本:#include #include #include #include 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); int(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_CUT)!= tempFileSize){ read(tempFd, tempBuf, 1024); printf("%sn", tempBuf); }//of while close(tempFd); return 0; }//of main
#include成功运行 总结#include #include #include #include int main(){ int tempFd=0; char tempFileName[20]="test.txt"; tempFd=open(tempFileName,O_RDWR|O_EXCL|O_TRUNC,S_IRWXG); if(tempFd==-1){ perror("file open error.n"); exit(-1); } //of if int tempLen=0; char tempBuf[100]={0}; scanf("%s",tempBuf); tempLen=strlen(tempBuf); write(tempFd,tempBuf,tempLen); close(tempFd); 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("%sn",tempBuf); } //of while close(tempFd); return 0; } //of main
更加熟练地掌握了Ubuntu的用法,学会使用几个C语言中的新函数,对系统级程序设计这门课程有了个初步的了解。其中特别需要注意的是几个C语言代码规范
int main(){ // 左大括号紧跟main函数
}
for(){
} // of for, if, while同理
// 驼峰命名法:
int tempFd;



