C语言中的IO操作
在计算机编程领域中,输入输出(Input/Output,简称IO)操作是非常重要的一部分。在C语言中,IO操作提供了一种机制,使程序能够与外部设备进行数据交互。本文将针对C语言中的IO操作进行详细探讨。
1. 标准输入输出(stdio.h)
标准输入输出是C语言中最基本的IO操作,使用stdio.h头文件中的函数实现。其中,最常用的函数包括printf、scanf、getchar和putchar。
1.1 printf函数
printf函数用于将数据输出到标准输出设备(通常是显示器)。它具有灵活的格式化输出功能,可以输出不同类型的数据,如字符串、整数、浮点数等。下面是一个示例:
```c
#include <stdio.h>
int main() {
    int num = 10;
    printf("The number is %d\n", num);
    return 0;
}
```
1.2 scanf函数
scanf函数用于从标准输入设备(通常是键盘)读取数据。它与printf函数相对应,可以按照指定的格式读取不同类型的数据。下面是一个示例:
```c
#include <stdio.h>
int main() {
    int num;
    printf("Please enter a number: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);
    return 0;
}
```
1.3 getchar和putchar函数
getchar函数用于从标准输入设备(通常是键盘)读取一个字符,putchar函数用于将一个字符输出到标准输出设备(通常是显示器)。下面是一个示例:
```c
#include <stdio.h>
int main() {
    char ch;
    printf("Please enter a character: ");
    ch = getchar();
    printf("You entered: ");
    putchar(ch);
    return 0;
}
```
2. 文件IO操作(stdio.h)
除了与标准输入输出相关的函数,C语言还提供了文件IO操作的函数,使程序可以读写文件。这些函数包括fopen、fclose、fread、fwrite等。
2.1 fopen和fclose函数
fopen函数用于打开一个文件,并返回一个文件指针,供后续的读写操作使用。fclose函数用于关闭一个文件。下面是一个示例:
```c
#include <stdio.h>
int main() {
    FILE *file;
    file = fopen("", "w");
    if (file == NULL) {
        printf("File open error!\n");
        return 1;
    }
    fprintf(file, "Hello, world!");
    fclose(file);
    return 0;
}
```
2.2 fread和fwrite函数
fread函数用于从文件中读取数据,fwrite函数用于将数据写入文件。下面是一个示例:
```c
#include <stdio.h>
typedef struct {
    int id;
    char name[20];
} Student;
int main() {
    FILE *file;
    Student student;
    file = fopen("students.dat", "rb");
fread和fwrite的区别    if (file == NULL) {
        printf("File open error!\n");
        return 1;
    }
    while (fread(&student, sizeof(Student), 1, file) == 1) {