Thread: Passing a string as argument to fgets

  1. #1
    Registered User
    Join Date
    May 2012
    Location
    Brazil
    Posts
    58

    Passing a string as argument to fgets

    Hello there,

    I'm trying to prompt the user for a file name (from main.c) and then pass that name as an argument to the fgets function (in file_op.c).

    In main.c, I did the following:
    Code:
    char *file = "testfile.txt";
    read_file(file);
    In file_op.c:
    Code:
    void read_file(char * name) {
    FILE *file = fopen(name, "r");
    if (file == NULL) {
    perror("Impossible to open file.");
    exit(EXIT_FAILURE);
    } char *line; while (fgets(line, 100, file) != NULL) { printf("%s", line); } }
    I'm getting a error in Netbeans about accessing memory.
    Could you guys help me? I'm not very familiar with this fgets function and all the examples I've found were not very helpful.

    Thanks a lot in advance.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You declare a pointer to char named line, but did not allocate any memory for the string, and did not even initialise the pointer.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The variable "line" is not pointing to any valid memory.

    char line[100];

    would be a much better way to go.

  4. #4
    Registered User
    Join Date
    May 2012
    Location
    Brazil
    Posts
    58
    That did it, thanks a lot both of you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. array of pointers passed as argument to fgets
    By shruthi in forum C Programming
    Replies: 16
    Last Post: 09-07-2012, 11:12 PM
  2. error: passing const std::string as this argument
    By noobcpp in forum C++ Programming
    Replies: 2
    Last Post: 07-23-2008, 01:11 PM
  3. Replies: 4
    Last Post: 04-21-2008, 12:15 PM
  4. Argument passing
    By Tarper67 in forum C++ Programming
    Replies: 1
    Last Post: 06-13-2003, 02:59 PM
  5. argument passing
    By theweirdo in forum C Programming
    Replies: 1
    Last Post: 01-29-2002, 07:42 PM