文件读取和输入输出

文件指针

在C语言中,文件操作是通过文件指针来进行的。文件指针是一个指向 FILE 结构的指针,用于标识和操作一个文件。

cpp 复制代码
FILE *fp;

常用的文件操作函数

  1. fopen:打开文件。
  2. fclose:关闭文件。
  3. fread:从文件中读取数据。
  4. fwrite:向文件中写入数据。
  5. fscanffprintf:格式化读取和写入。
  6. fgetsfputs:读取和写入字符串。
  7. fseek:设置文件指针的位置。
  8. ftell:获取文件指针的位置。

打开文件 (fopen)

fopen 函数用于打开文件,并返回一个文件指针。如果打开失败,返回 NULL

cpp 复制代码
FILE *fopen(const char *filename, const char *mode);

常用模式:

  1. "r":只读模式。
  2. "w":写模式,文件不存在则创建,存在则清空。
  3. "a":追加模式,文件不存在则创建。
  4. "r+":读写模式,文件必须存在。
  5. "w+":读写模式,文件不存在则创建,存在则清空。
  6. "a+":读写追加模式,文件不存在则创建。

关闭文件 (fclose)

fclose 函数用于关闭文件,释放资源。

cpp 复制代码
int fclose(FILE *fp);

读取文件

fread

fread 函数从文件中读取数据到缓冲区。

cpp 复制代码
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

fscanf

fscanf 函数从文件中读取格式化数据。

cpp 复制代码
int fscanf(FILE *stream, const char *format, ...);

fgets

fgets 函数从文件中读取一行字符串。

cpp 复制代码
char *fgets(char *str, int n, FILE *stream);

写入文件

fwrite

fwrite 函数向文件中写入数据。

cpp 复制代码
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

fprintf

fprintf 函数向文件中写入格式化数据。

cpp 复制代码
int fprintf(FILE *stream, const char *format, ...);

fputs

fputs 函数向文件中写入字符串。

cpp 复制代码
int fputs(const char *str, FILE *stream);

文件指针操作

fseek

fseek 函数设置文件指针的位置。

cpp 复制代码
int fseek(FILE *stream, long offset, int whence);
//SEEK_SET:文件开头。
//SEEK_CUR:当前位置。
//SEEK_END:文件末尾。

ftell

ftell 函数获取当前文件指针的位置。

cpp 复制代码
long ftell(FILE *stream);

错误处理

文件操作过程中可能会遇到错误,常用的错误处理函数包括:

  • ferror:检查文件指针是否有错误。
  • feof:检查文件指针是否到达文件末尾。
  • perror:打印错误信息。

读取文件内容并打印

cpp 复制代码
#include <stdio.h>

int main() {
    FILE *fp = fopen("example.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    char buffer[100];
    while (fgets(buffer, 100, fp) != NULL) {
        printf("%s", buffer);
    }

    fclose(fp);
    return 0;
}

向文件写入数据

cpp 复制代码
#include <stdio.h>

int main() {
    FILE *fp = fopen("output.txt", "w");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    fprintf(fp, "Hello, World!\n");
    fputs("This is a test.\n", fp);

    fclose(fp);
    return 0;
}

总结

|----------|----------------|---------------------------------------------------------------------|------------------------------------------|
| fopen | 打开文件,并返回文件指针 | FILE *fopen(const char *filename, const char *mode); | FILE *fp = fopen("file.txt", "r"); |
| fread | 从文件中读取数据到缓冲区 | size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); | fread(buffer, sizeof(char), 100, fp); |
| fscanf | 从文件中读取格式化输入 | int fscanf(FILE *stream, const char *format, ...); | fscanf(fp, "%d", &num); |
| fgets | 从文件中读取一行字符串 | char *fgets(char *str, int n, FILE *stream); | fgets(buffer, 100, fp); |
| fgetc | 从文件中读取一个字符 | int fgetc(FILE *stream); | char c = fgetc(fp); |
| fseek | 设置文件指针的位置 | int fseek(FILE *stream, long offset, int whence); | fseek(fp, 0, SEEK_SET); |
| ftell | 获取文件指针的位置 | long ftell(FILE *stream); | long pos = ftell(fp); |
| fclose | 关闭文件,释放资源 | int fclose(FILE *fp); | fclose(fp); |
| feof | 检查文件指针是否到达文件末尾 | int feof(FILE *stream); | if (feof(fp)) { /* End of file */ } |
| ferror | 检查文件指针是否有错误 | int ferror(FILE *stream); | if (ferror(fp)) { /* Handle error */ } |
| perror | 打印错误信息 | void perror(const char *str); | perror("Error opening file"); |

打开并读取文件

cpp 复制代码
#include <stdio.h>

int main() {
    FILE *fp;
    char buffer[100];
    int num;

    // 打开文件
    fp = fopen("example.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    // 使用 fgets 读取一行字符串
    if (fgets(buffer, 100, fp) != NULL) {
        printf("Read string: %s\n", buffer);
    }

    // 使用 fscanf 读取格式化输入
    if (fscanf(fp, "%d", &num) == 1) {
        printf("Read integer: %d\n", num);
    }

    // 关闭文件
    fclose(fp);

    return 0;
}

使用 fread 读取二进制文件

cpp 复制代码
#include <stdio.h>

int main() {
    FILE *fp;
    char buffer[100];
    size_t bytesRead;

    // 打开二进制文件
    fp = fopen("example.bin", "rb");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    // 使用 fread 读取数据到缓冲区
    bytesRead = fread(buffer, sizeof(char), 100, fp);
    printf("Bytes read: %zu\n", bytesRead);

    // 关闭文件
    fclose(fp);

    return 0;
}

输入输出

|-----------|---------------------|-----------------|------------------------------|
| printf | 格式化输出到标准输出(通常是屏幕) | 向控制台打印各种格式化的数据 | printf("Hello, World!\n"); |
| scanf | 从标准输入(通常是键盘)读取格式化输入 | 从用户输入获取各种格式化的数据 | scanf("%d", &num); |
| getchar | 从标准输入读取单个字符 | 读取单个字符 | char c = getchar(); |
| putchar | 向标准输出写入单个字符 | 输出单个字符 | putchar('A'); |

printf 示例

printf 用于格式化输出,可以打印整数、浮点数、字符串等。

cpp 复制代码
#include <stdio.h>

int main() {
    int num = 10;
    float f = 3.14;
    char str[] = "Hello, World!";
    
    // 使用 printf 打印各种类型的数据
    printf("Integer: %d\n", num);
    printf("Float: %.2f\n", f);
    printf("String: %s\n", str);
    
    return 0;
}

scanf 示例

scanf 用于格式化输入,可以从用户输入获取整数、浮点数、字符串等。

cpp 复制代码
#include <stdio.h>

int main() {
    int num;
    float f;
    char str[50];
    
    // 提示用户输入数据
    printf("Enter an integer: ");
    scanf("%d", &num);
    
    printf("Enter a float: ");
    scanf("%f", &f);
    
    printf("Enter a string: ");
    scanf("%s", str);
    
    // 打印用户输入的数据
    printf("You entered: %d, %.2f, %s\n", num, f, str);
    
    return 0;
}

getchar 示例

getchar 用于读取单个字符,可以用于处理字符输入。

cpp 复制代码
#include <stdio.h>

int main() {
    char c;
    
    // 提示用户输入一个字符
    printf("Enter a character: ");
    c = getchar();
    
    // 打印用户输入的字符
    printf("You entered: %c\n", c);
    
    return 0;
}

putchar 示例

putchar 用于输出单个字符,可以用于处理字符输出。

cpp 复制代码
#include <stdio.h>

int main() {
    char c = 'A';
    
    // 输出字符
    printf("Character output: ");
    putchar(c);
    putchar('\n');
    
    return 0;
}
相关推荐
SPC的存折3 小时前
1、Redis数据库基础
linux·运维·服务器·数据库·redis·缓存
爱学习的小囧4 小时前
VMware ESXi 6.7U3v 新版特性、驱动集成教程和资源包、部署教程及高频问答详情
运维·服务器·虚拟化·esxi6.7·esxi蟹卡驱动
小疙瘩4 小时前
只是记录自己发布若依分离系统到linux过程中遇到的问题
linux·运维·服务器
dldw7775 小时前
IE无法正常登录windows2000server的FTP服务器
运维·服务器·网络
我是伪码农5 小时前
外卖餐具智能推荐
linux·服务器·前端
汤愈韬6 小时前
下一代防火墙通用原理
运维·服务器·网络·security
IMPYLH6 小时前
Linux 的 od 命令
linux·运维·服务器·bash
数据雕塑家8 小时前
Linux下大文件切割与合并实战:解决FAT32文件系统传输限制
linux·运维·服务器
IMPYLH8 小时前
Linux 的 nice 命令
linux·运维·服务器·bash
yleihj9 小时前
vCenter计算机SSL证书续期
服务器·网络协议·ssl