C程序设计:如何读取整个文件内容到缓冲区 [英] C Programming: How to read the whole file contents into a buffer

查看:117
本文介绍了C程序设计:如何读取整个文件内容到缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要到一个文件的全部内容写入到缓冲区中。该文件实际上只包含一个字符串,我需要一个字符串比较。

I want to write the full contents of a file into a buffer. The file actually only contains a string which i need to compare with a string.

什么是最有效的选择是便携式甚至在Linux上。

What would be the most efficient option which is portable even on linux.

ENV:视窗

推荐答案

便携性是大伤脑筋,因为Linux是一个POSIX的一致性系统 - 一般 - 一个合适的,高品质的工具链C,而Windows甚至不提供很多功能在C标准库。

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

不过,如果你要坚持标准,你可以这样写:

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  //same as rewind(f);

char *string = malloc(fsize + 1);
fread(string, fsize, 1, f);
fclose(f);

string[fsize] = 0;

下面字符串将包含文本文件的内容作为一个正常0终止的C字符串。这code是只是标准​​的C,它不是POSIX特有的(尽管它不出示担保,将工作/ Windows上编译...)

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't gurantee it will work/compile on Windows...)

这篇关于C程序设计:如何读取整个文件内容到缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆