【问题标题】:reading from a file inside fread() while loop从 fread() while 循环中的文件读取
【发布时间】:2022-01-21 03:21:39
【问题描述】:

我正在处理问题集 4“内存”并试图了解 fread() 函数以及在 fread() 的 while 循环中使用 fread() 的工作原理。我正在尝试读取文件直到文件结束,这就是我的 while 循环的用途,然后当我找到 JPEG 文件签名时,我想从该文件中读取,直到找到下一个 JPEG 签名。我的问题是这对于 fread() 函数的两个单独调用如何工作?一旦我找到文件签名并开始在while循环中使用fread()从文件中读取,然后在退出我的if条件后迭代该while循环,while(fread())是否会拾取fread()在while循环中停止的地方?请看下面的代码:

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

// using keyword typedef to give the uint8_t a new name of BYTE (capitalized by convention)
typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // must be two arguments or program not run correctly
    if(argc != 2)
    {
        printf("Usage: ./recover filename\n");
        return 1;
    }

// open file and store its location in a pointer called infile
FILE *infile = fopen(argv[1], "r");
if(infile == NULL)
{
    printf("file cannot be opened or doesnt exist...\n");
    return 1;
}

// read using fread(), each 512 byte block into a buffer
//need a buffer of size 512 BYTEs
BYTE buffer[512];
while(fread(&buffer, sizeof(BYTE), 512, infile))
{
    // create buffer to store a filename with a formatted string of ###.jpg starting at 000.jpg
    int number = 0;
    char filename[8];

    sprintf(filename, "%03i.jpg", number);

    // this demarks a JPEG using bitwise logical & for last buffer bit of signature
    if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        
        // this will be the first signature read and start of a JPEG
        if(number == 0)
        {
        // open new file
        FILE *img = fopen(filename, "w");
        // write what is currently in buffer into file
        fwrite(&buffer, sizeof(BYTE), 512, img);
        
        // continue reading from file where left off and write it to img file until a new file signature?
        while(fread(&buffer, sizeof(BYTE), 512, infile))
        {
            fwrite(&buffer, sizeof(BYTE), 512, img)
            if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
            {
                break;
            }
        }

我的问题是关于在 while 循环内对 fread() 的第二次调用,以及对 fread() 的调用如何影响对初始 while 循环的 fread() 的调用。希望这是有道理的。

【问题讨论】:

  • 您只需要在由fread() 结果控制的循环中调用一个fread()。如果该块是签名块,则关闭输出文件(如果它已打开),打开一个新文件,然后增加文件编号。然后fwrite() 数据块。循环结束后,关闭文件。
  • ...表示您总共需要 一个 fread() 通话和 一个 fwrite() 通话。您通过定义FILE *img = NULL 开始程序,以便在循环内部知道输出文件是否打开。
  • 好的,谢谢,今天让我再试一次。但是,我仍然很好奇程序中的多个 fread() 调用是如何工作的,它是否会从该文件中最后一个 fread() 停止的位置开始?
  • 它从内部更新的文件位置读取。 fread 调用的排列方式没有任何区别:除非您将 fseek 转到另一个文件位置,否则将读取下一个块。我早期的 cmets 旨在指出您使解决方案变得比需要的更困难。你甚至复制了标题块的测试。
  • 我已经找到解决办法了,谢谢你的帮助!

标签: c cs50 fread


【解决方案1】:

我认为您已经在 cmets 中找到了解决方案。 您还可以在此处使用函数和递归。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-05
    • 2017-10-12
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多