fread rb+_C / C ++中的fread()完整指南

fread rb+

In this article, we’ll take a look at using fread() in C/C++.

在本文中,我们将介绍在C / C ++中使用fread()的方法。

The fread() function is very useful if you want to store the contents of reading a file into a buffer. Let’s take a look at how we can use this function, using some illustrative examples!

如果要将读取文件的内容存储到缓冲区中,则fread()函数非常有用。 让我们来看一些示例,看看如何使用此功能!



C / C ++中fread()的基本语法 (Basic Syntax of fread() in C/C++)

This function will read a certain number of characters from a file and store in inside a buffer.

此功能将从文件中读取一定数量的字符,并将其存储在缓冲区内。

We can specify the number of characters and the buffer as well as the file.

我们可以指定字符数,缓冲区以及文件。

This makes it pretty easy to read a file stream-wise and not waste your memory loading it all at once, if your file is large!

如果您的文件很大,那么就很容易按流读取文件,而不会浪费您的内存一次加载所有文件!

The function prototype is as follows:

函数原型如下:


size_t fread(void * buffer, size_t size, size_t count, FILE* fp);

This takes in a file pointer fp, and reads count elements, each with a size of size. This will store the contents into a buffer, passed as a void* pointer.

这接收文件指针fp ,并读取count元素,每个元素的大小为size 。 这会将内容存储到缓冲区中,作为void*指针传递。

This will return the number of elements read. Usually, if our read is successful, we’ll get it as count. Otherwise, we’ll obviously get a number lesser than it!

这将返回读取的元素数。 通常,如果读取成功,则将其作为count 。 否则,我们显然会得到比它小的数字!

Because of the return value, it is very easy to check for the EOF condition!

由于有返回值,因此很容易检查EOF条件!

Let’s take a look at a simple example now, to illustrate our point.

现在让我们看一个简单的例子,以说明我们的观点。



在C / C ++中使用fread()–一些简单的例子 (Using fread() in C/C++ – Some simple examples)

Now, we’ll take an input file containing the following content:

现在,我们将获取一个包含以下内容的输入文件:


Hello, this is from JournalDev.
This is an article regarding the fread() function.
We'll read this file in chunks of 6 characters each!

Save this as input.txt, and we’ll pass this as a file pointer FILE* fp.

将其保存为input.txt ,我们将其作为文件指针FILE* fp传递。

We’ll take a huge buffer size (let’s say 1024 bytes). We can pass count to be 1024, but fread() will terminate as soon as we reach EOF. Let’s verify this.

我们将使用巨大的缓冲区大小(假设为1024个字节)。 我们可以将count传递为1024,但是一旦到达EOF, fread()将终止。 让我们验证一下。


#include <stdio.h>
#include <string.h>

int main() {
    FILE* fp = fopen("input.txt", "r");

    // We'll store the contents onto a buffer
    char buffer[1024];

    // Number of characters read
    size_t num_read = fread(buffer, sizeof(char), 1024, fp);

    if (num_read < 1024) printf("Reached EOF!\n"); 
    
    // We must explicitly NULL terminate the buffer with '\0'
    buffer[num_read] = '\0';

    printf("Read %lu characters\n", num_read);

    printf("Buffer: %s\n", buffer);

    fclose(fp);
    return 0;
}

Output

输出量


Reached EOF!
Read 136 characters
Buffer: Hello, this is from JournalDev.
This is an article regarding the fread() function.
We'll read this file in chunks of 6 characters each!

Indeed, we reach EOF, since we have only 136 characters inside our file! As expected, the buffer contains the entire file.

确实,我们达到了EOF,因为文件中只有136个字符! 如预期的那样,缓冲区包含整个文件。

Here, you must be very careful to NULL terminate the buffer with '\0'. fread() does NOT terminate a string by itself. That’s why we set the last element read to be \0.

在这里,您必须非常小心,以NULL终止'\0'缓冲区。 fread()本身不会终止字符串。 这就是为什么我们将最后一个元素设置为\0

Now, let’s take another case – if the file size is greater than the buffer size, we have to read the file in chunks. We’ll take count = 20, so that we read 20 characters at a time.

现在,让我们考虑另一种情况–如果文件大小大于缓冲区大小,则必须分块读取文件。 我们将count = 20 ,这样我们一次读取20个字符。

In this case, we’ll use fread() using a while() loop, checking it’s return value for EOF. If it has read less than 20 characters, we immediately break out of the loop and then NULL terminate the buffer string.

在这种情况下,我们将使用while()循环使用fread() ,检查它是否为EOF返回值。 如果读取的字符数少于20 ,我们将立即退出循环,然后使用NULL终止缓冲区字符串。


#include <stdio.h>
#include <string.h>

int main() {
    FILE* fp = fopen("input.txt", "r");

    // We'll store the contents onto a buffer
    char buffer[256];

    // Number of characters read
    int num_read;

    size_t total_read = 0;

    // Number of chars to read at a time
    size_t count = 20;

    while ((num_read = fread(buffer + total_read, sizeof(char), count, fp)) == count) {
        // As long as we read <count = 20> characters, we'll be in this loop
        printf("Read %lu characters (%s) into buffer\n", count, buffer + total_read);
        total_read += 20;
    }

    // If num_read is less than 6, we've reached EOF
    total_read += num_read;

    buffer[total_read] = '\0';

    printf("Read %lu characters\n", total_read);

    printf("Buffer: %s\n", buffer);

    fclose(fp);
    return 0;
}

Output

输出量


Read 20 characters (Hello, this is from ) into buffer
Read 20 characters (JournalDev.
This is ) into buffer
Read 20 characters (an article regarding) into buffer
Read 20 characters ( the fread() functio) into buffer
Read 20 characters (n.
We'll read this f) into buffer
Read 20 characters (ile in chunks of 6 c0,!Y) into buffer
Read 136 characters
Buffer: Hello, this is from JournalDev.
This is an article regarding the fread() function.
We'll read this file in chunks of 6 characters each!

While the output may look incorrect on first glance, there is no problem!

乍一看,输出可能看起来不正确,但这没有问题!

This is because fread() didn’t NULL terminate the strings, so when printing it, some garbage values were printed, since we don’t have '\0` yet, as we are still adding characters to the buffer.

这是因为fread()不会以NULL终止字符串,因此在打印时,会打印一些垃圾值,因为我们还没有'\0` ,因为我们仍在向缓冲区添加字符。

So, the confirmation of the output is the final buffer itself. So indeed, we were able to read the file in chunks and print it all!

因此,输出的确认是最终缓冲区本身。 因此,的确,我们能够读取文件并全部打印!



结论 (Conclusion)

In this article, we looked at using fread() in C/C++. This makes it very easy to read stream-wise from an input file. It also has a very useful return value that we can use to verify terminating conditions.

在本文中,我们研究了在C / C ++中使用fread()的方法。 这使得从输入文件中按流读取非常容易。 它还有一个非常有用的返回值,我们可以用来验证终止条件。

参考资料 (References)



翻译自: https://www.journaldev.com/40399/fread-in-c-plus-plus

fread rb+

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值