栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

系统级程序设计(一)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

系统级程序设计(一)

文章目录
  • 引入
  • 课程内容
    • 代码错误
    • 修改后可运行的版本:
    • 成功运行
  • 总结

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;
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853159.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号