Home > Software design >  Unable to read from file from argv
Unable to read from file from argv

Time:09-08

I am trying to read from a file, and here is my code, but as I run my code nothing shows up. Have I used the getline() function incorrectly? I can not understand my problem.

const char *READ = "r";
    
    /**
     * main - Entry point of my program
     *
 * Return: On success, it returns 0. On
 * error it returns -1
 */
int main(int ac, char **av)
{
        FILE *fpointer;
        char *lineptr = NULL;
        size_t *n = 0;
        int line_number = 1;

        if (ac != 2)
        {
                fprintf(stderr, "USAGE: monty file\n");
                exit(EXIT_FAILURE);
        }

        fpointer = fopen(av[1], READ);
        if (fpointer == NULL)
        {
                fprintf(stderr, "Error: Can't open file %s\n", av[1]);
                exit(EXIT_FAILURE);
        }
        while (getline(&lineptr, n, fpointer) != -1)
        {
                printf("Line %d: %s\n", line_number, lineptr);
                line_number  ;
        }
        return (0);
}

CodePudding user response:

Declaration of getline:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

As an output parameter, the type of n is size_t *. It points to a space for writing by getline.

But in your code, n points to 0, which is NOT a vaild addr to write in.

CodePudding user response:

getline(&lineptr, n, fpointer) returns -1. You did not explicitly check this and print an error message.

Checking errno it's because of EINVAL: invalid argument. Also good to check errno.

Reason is that n is NULL, while a pointer to an existing size_t is required.

BTW, indenting with 8 spaces is rather uncommon; I'd stay with 4 space. (Also, never use TAB characters.)

It's advisable to stick with extremely common argc and argv.

Nice you put {s on a further empty line; I like that style.

You'd get this:

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

const char *READ = "r";

int main(int argc, char **argv)
{
    FILE *fpointer;
    char *lineptr = NULL;
    size_t *n = 0;
    int line_number = 1;

    if (argc != 2)
    {
        fprintf(stderr, "USAGE: monty file\n");
        exit(EXIT_FAILURE);
    }

    fpointer = fopen(argv[1], READ);
    if (fpointer == NULL)
    {
        fprintf(stderr, "Error: Can't open file '%s'.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    if (getline(&lineptr, n, fpointer) == -1)
    {
        printf("Failed to read file '%s': %s.\n", argv[1], strerror(errno));
        exit(EXIT_FAILURE);
    }

    do
    {
        printf("Line M: %s\n", line_number, lineptr);
        line_number  ;
    }
    while (getline(&lineptr, n, fpointer) != -1);

    return (0);
}
  • Related