HelloMonster
HelloMonster

Reputation: 39

How to use fread or fgets to read file until certain string in C?

I have having a file contains some message eg.

Hello world.\n
..\n
.\r\n

And I want to use fread() or fgets() to read everything up to ".\r\n", so the expected message should be:

Hello world.\n
..\n

and store it into a char buffer to print out? I am wondering if someone can give me some ideas? Thanks!

Upvotes: 1

Views: 1373

Answers (1)

abhate
abhate

Reputation: 115

This code works

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

int main()
{
    FILE *file = fopen("file.txt", "rb"); /* Replace file.txt with your file name */
    /* Get the size of the file */
    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fseek(file, 0, SEEK_SET);
    /* Allocate memory for the file content */
    char *content = calloc(size + 1, sizeof(char)); /* calloc() initialises all memory to zero */
    /* Read the file content into memory */
    fread(content, sizeof(char), size, file);
    fclose(file);
    /* Find \r\n in file */
    char *pos = strstr(content, "\r\n"); /* strstr() finds the first occurrence of the substring */
    if (pos == NULL) {
        /* The file does not have \r\n so is not valid */
        fprintf(stderr, "The file is not valid\n");
        return 1;
    }
    /* Null terminate the string to hide \r\n */
    /* Data after it still remains but is not accessed */
    *pos = '\0';
    /* Do whatever you want with the file content */
    /* Free the memory */
    free(content);
    return 0;
}

Upvotes: 2

Related Questions