0%

Linux程序设计-gdb程序调试工具 [总结概况版][复习专用][速通]

导航

当前章节:gdb程序调试工具
原文链接:gdb程序调试工具
上一章节:shell脚本
下一章节:文件IO
目录:Linux程序设计

文件io

介绍

在linux系统中一切皆文件,有文本文件,配置文件,可执行文件…。大部分资源都是以文件形式存在的,如在通信时的sock文件。

linux的文件存放在磁盘中,在操作系统中读写操作属于内核级,用户程序使用需要借助系统调用,即linux实现的一个系统级函数。
必须通过这个函数才能对文件操作。当然c语言也有文件操作函数,但是该函数本身是借助系统调用的,对其进行了封装和扩展。

system call系统调用形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int fd = creat(filename, mode); 	 
creat() can only be used to open files for writing.

int fd = open(filename, flags, mode);
int fd = open("file.txt", O_RDONLY | O_CREAT, 0644);

close(fd);

ssize_t read(int fd, void *buf, size_t count);
char buf[100];
read(3, buf, 100);

ssize_t write(int fd, const void *buf, size_t count);
char data[50];
write(7, data, 50);
  • filename is the name of the file to open.
  • flags specifies the mode to open the file in (read, write, append, etc.)
    Some common flags are:
  • O_RDONLY - Open for read only
  • O_WRONLY - Open for write only
  • O_RDWR - Open for read and write
  • O_APPEND - Append to end of file
  • O_CREAT - Create file if it does not exist

1.creat()总是将文件截断为0个字节。如果同时使用O_APPEND,则带有O_CREAT的open()不会截断。
2.creat()需要模式参数。使用open(),该模式是可选的。
3.creat()只能用于打开文件进行写入。open()接受其他标志,如O_RDONLY、O_RDWR等。
4.creat()返回一个仅为写入而打开的文件描述符。open()返回一个基于标志的描述符,该描述符可以是只读的或读写的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

### cfunction C语言函数形式
```c
FILE *fptr = fopen(filename, mode);
- "r" - Read (the default)
- "w" - Write (will overwrite!)
- "a" - Append
- "r+" - Read and write

fclose(fptr);

Some common operations on FILE pointers are:
- fgetc() - Read a character
- fputc() - Write a character
- fgets() - Read a string
- fputs() - Write a string
- fscanf() - Read formatted input
- fprintf() - Write formatted output
- fread() - Read raw data
- fwrite() - Write raw data
- feof() - Check if at end of file or use (c = fgetc(fptr)) != EOF
- fflush() - Flush output buffer

read/write和 C语言IO函数之间的一些主要区别:

  • read/write 对文件描述符进行操作,fread/fwrite 对 FILE 指针进行操作。
  • read/write级别更低。 stdio 函数提供更高级别的文件 I/O。
  • read/write做原始 I/O。 stdio 可以格式化输入/输出。
  • 缓冲 - stdio 处理缓冲,对于read/write,您必须手动处理任何缓冲。
  • 错误检查 - stdio 函数在出错时返回 EOF/-1。 必须检查的read/write设置错误号。

使用read/write而不是IO函数的场景

  • 用于 Linux 系统调用和 C 编程
  • 当优先考虑低水平控制和效率时
  • 与非 C 接口/库的互操作性
  • 在内核空间编程

对于大多数用户空间 C 程序,IO函数更容易,并且推荐用于可移植性和兼容性。