C语言如何进行文件操作

发布时间:2025-02-15 00:30:36 作者:小樊
来源:亿速云 阅读:95

在C语言中,文件操作主要通过标准库函数来实现。以下是一些常用的文件操作函数及其用法:

打开文件

使用fopen函数打开一个文件,并返回一个文件指针。

FILE *fopen(const char *filename, const char *mode);

示例:

FILE *file = fopen("example.txt", "r");
if (file == NULL) {
    perror("Failed to open file");
    return 1;
}

关闭文件

使用fclose函数关闭一个已打开的文件。

int fclose(FILE *stream);

示例:

fclose(file);

读取文件

使用fread函数从文件中读取数据。

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

示例:

char buffer[1024];
size_t bytesRead = fread(buffer, sizeof(char), sizeof(buffer) - 1, file);
if (bytesRead > 0) {
    buffer[bytesRead] = '\0'; // Null-terminate the string
    printf("Read %zu bytes: %s
", bytesRead, buffer);
}

写入文件

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

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

示例:

const char *data = "Hello, World!";
size_t bytesWritten = fwrite(data, sizeof(char), strlen(data), file);
if (bytesWritten > 0) {
    printf("Wrote %zu bytes
", bytesWritten);
}

定位文件指针

使用fseek函数移动文件指针。

int fseek(FILE *stream, long offset, int whence);

示例:

fseek(file, 0, SEEK_SET); // 将文件指针移动到文件开头

获取文件信息

使用fstat函数获取文件信息。

int fstat(int fd, struct stat *buf);

示例:

struct stat fileStat;
if (fstat(fileno(file), &fileStat) == 0) {
    printf("File size: %ld bytes
", fileStat.st_size);
}

删除文件

使用remove函数删除一个文件。

int remove(const char *pathname);

示例:

if (remove("example.txt") == 0) {
    printf("File deleted successfully
");
} else {
    perror("Failed to delete file");
}

这些是C语言中进行文件操作的基本函数和方法。根据具体需求,可以选择合适的函数进行文件读写、定位和删除等操作。

推荐阅读:
  1. C语言中如何使用getch()读取方向键
  2. C语言怎么实现I/O流设计

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言

上一篇:C语言中结构体怎么用更高效

下一篇:C语言怎样处理字符串

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》