简体   繁体   中英

How to read from a file when passing path as an argument using realpath()

I want to pass an argument of a specific file location using realpath() (example: /var/log/message ) and by using fprintf print the content of this file on the terminal. This is the code I have so far:

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

int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("Usage: %s <path>\n", argv[0]);
        return 1;
    }
    char *fullpath = realpath(argv[1], NULL);
    FILE *fptr;
    fptr = fopen(fullpath, "r");
    fprintf(fptr, "%s");
    return 0;
}

It doesn't throw errors, but it also doesn't do what I want it to do. When I run it eg ./test /var/log/message it will show me this on the terminal:

Segmentation fault (core dumped)

OS version

NAME="Fedora Linux"
VERSION="36

Compiler

gcc

Got back to my function and added some more functionality and now it's working with adding argument for it.

Current code:

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

int main(int argc, char **argv)
{
    FILE *fptr;
    char c;
    if (argc < 2) {
        printf("You need to grant an arg to %s <path>\n", argv[0]);
        return 1;
    }
    char *fullpath = realpath(argv[1], NULL);
    fptr = fopen(fullpath, "r");
    if (fptr == NULL)
    {
        printf("Cannot open file \n");
        exit(0);
    }
    c = fgetc(fptr);
    while (c != EOF)
    {
        printf ("%c", c);
        c = fgetc(fptr);
    }
    fclose(fptr);
    return 0;
}

Thanks all for your assistance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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