系统级程序设计总结笔记(一)
侧边栏壁纸
  • 累计撰写 40 篇文章
  • 累计收到 134 条评论

系统级程序设计总结笔记(一)

yjprolus
2022-05-02 / 2 评论 / 17 阅读 / 正在检测是否收录...
Ubuntu20.04之前已经装好了,也一直在用,和服务器版本相同(师傅们别打了 )。博客也快两个月没水文章了,但是笔记都有在坚持做,只是没什么时间(bushi)搬运到博客和个人网站上。最近Python写多了,写C语言时分号老忘写...

引入

温习下之前学过的C语言相关文件操作函数:
在这里插入图片描述

课程内容

首先是简单介绍了下这门课程的重要性,接着回顾了Linux的一些相关知识。后面就是在Ubuntu下使用Codeblocks进行C编程了

代码错误

代码主要功能是用open函数打开test.txt并将文件内容清空,用write函数将read函数读取到的数据打印出来,简单讲就是把输入的一行字符串输出到控制台并写入指定文件中

下面是老师提供的源代码,有几处错误
在这里插入图片描述

  • 24行的 int 应改为 if
  • 31行的参数 Codeblocks 提示有误,应为 SEEK_CUR
#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);
    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("%s\n", tempBuf);
    }//of while
    close(tempFd);
    return 0;
}//of main

修改后可运行的版本:

#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";

    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("%s\n",tempBuf);
    } //of while
    close(tempFd);
    return 0;
} //of main

成功运行

在这里插入图片描述

总结

更加熟练地掌握了Ubuntu的用法,学会使用几个C语言中的新函数,对系统级程序设计这门课程有了个初步的了解。其中特别需要注意的是几个C语言代码规范

int main(){  // 左大括号紧跟main函数
}

for(){

} // of for, if, while同理

// 驼峰命名法:
int tempFd;
0

评论 (2)

取消
  1. 头像
    伊朗悍妇
    Windows 8.1 · Google Chrome

    都是干货

    回复
  2. 头像
    骑着蜗牛追导弹
    Windows 7 · FireFox

    牛啊牛啊

    回复