繁体   English   中英

从 fread() while 循环中的文件读取

[英]reading from a file inside fread() while loop

我正在处理问题集 4“内存”并试图了解 fread() function 以及在 fread() 的 while 循环中使用 fread() 的工作原理。 我正在尝试读取文件直到文件结束,这就是我的 while 循环的用途,然后当我找到 JPEG 文件签名时,我想从该文件中读取,直到找到下一个 JPEG 签名。 我的问题是这对于 fread() function 的两个单独调用如何工作? 一旦我找到文件签名并开始在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() 的调用。 希望这是有道理的。

我想你已经在评论中找到了解决方案。 您还可以在此处使用函数和递归。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM