1

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!

  • 1
    Read each line using `fgets` in a loop. You probably want to remove the newline from the buffer. Stop reading the the buffer is equal to the line you want to stop at (`strcmp(buffer, ".") == 0`). – Some programmer dude Dec 07 '21 at 07:54
  • If you need to distinguish `\n` from `\r\n` I suggest opening the file in **binary** mode. – Weather Vane Dec 07 '21 at 07:57
  • Are you sure about the `\r\n`? This is rather odd. Isn't it just `\n`? What is your platform? This might be interesting as well: https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input – Jabberwocky Dec 07 '21 at 07:59
  • 1
    It would be unusual to have two different line ending styles in the same file: they are system-related. – Weather Vane Dec 07 '21 at 08:04
  • 1
    The question also asks how to read a file using `fgets()` of `fread()` and store in a buffer: do that first and show the code. Use `fgets()` and not `fread()` on a text file. Then, open the file in `"rb"` mode and look for the presence of 'return' character with `if(strchr(buf, '\r') != NULL)` – Weather Vane Dec 07 '21 at 08:11

1 Answers1

2

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;
}
abhate
  • 95
  • 1
  • 6