#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    20
    Rep Power
    0

    Storing lines from file into char *


    First and foremost I would like to thank everyone on this forum for there help. Ever since I've joined it seems that I am learning so much faster with the help and explanations of people on here and I'm greatly appreciative towards it.

    So here is my issue. I have a struct..

    Code:
    struct node{
       char* a;
       char* b;
       struct node *next;
       struct node *prev;
    };
    using this along with fgets I wanted to save lines of the file in my linked list. The problem is, is that when saving since char* a is a pointer every time I pull a new line using fgets and assign my char pointer both a and b point to the new line and never keep the existing line for example.

    Code:
    struct node *test;
    test = malloc(sizeof(struct node));
    test->next = NULL;
    test->prev = NULL;
    test->a = NULL;
    test->b= NULL;
    FILE *filePointer;
    filePointer = fopen("location/to/file/txt", "r");
    char temp[200];
    while(fgets(temp, 200, filePointer) != NULL){
        if(some condition){
            test->a = temp; 
        } else {
            test->b = temp; //when this next condition is met
        }                         // both a and b will point to
    }                             //current temp and I lose all previous lines
    How can I get around this issue?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    156
    Rep Power
    34
    You need to allocate memory and copy the data from the file to the newly allocated memory and make a and b point to that memory.

    Remember to free the resources when you no longer need them.
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,905
    Rep Power
    481
    adding a bit to bdb's post, investigate these functions:
    malloc
    strdup
    free
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Permanently Banned
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    4
    Rep Power
    0

    Storing


    You can use vector as:

    std::ifstream file("file.txt");
    std::istreambuf_iterator<char> begin(file), end;
    std::vector<char> v(begin, end); //it reads the entire file into v

    char *contentOfTheFile= &v[0];

    The content of the file is stored in contentOfTheFile. You can use it, and modify it as well.

    check dapfor. com/en/net-suite/net-grid/features/conditional-binding for more details

    Comments on this post

    • dwise1_aol disagrees : vector is a C++ class. By all appearances, the OP is using C. Not the same language. One of the tricks in this forum is to figure out what language they're using.
    • Scorpions4ever disagrees : The guy doesn't know what he's talking about. He's just cut/pasting his replies from the web. See http://stackoverflow.com/questions/10865888/how-to-store-a-file-in-a-char for details
    Last edited by Scorpions4ever; September 21st, 2012 at 01:19 AM.
  8. #5
  9. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,184
    Rep Power
    2222
    arbitraryproc, here's what's happening in your program, as you corrected describe in your comments:
    Code:
    while(fgets(temp, 200, filePointer) != NULL){
        if(some condition){
            test->a = temp; 
        } else {
            test->b = temp; //when this next condition is met
        }                         // both a and b will point to
    }                             //current temp and I lose all previous lines
    test->a, test->b, and temp are all pointers which serve the function of "string". Now, in a number of languages with a built-in string type, you are able to copy a string from one string-type to another with a simple assignment statement, just as you tried to do here -- BTW, C++'s basic string type allows this as well, but then you are working in C here. C does not have a built-in string type, so it instead uses char arrays and char pointers, along with a suite of string functions prototyped in strings.h . The simple truth is that if you assign one pointer variable to another, then both pointers just end up pointing to the same location. Just as you noticed had happened. Read the code for what it does: assigning one pointer to another just points them both to the same thing.

    If you want to copy a string to another "string variable", then you need to actually copy that string from one location to another. It's not built into the language, so you have to do it explicitly. strings.h provides you with a function, strcpy, which does that work for you. And the exact same applies to anything you access through pointers and want to make a copy of, most commonly structs.

    An additional point to always keep in mind. If you have a string that you want to copy to a char pointer, then you first need to make sure that that destination char pointer is pointing to actual memory that you can use. As you had declared those destination pointers, they initially point to NULL, which in Intel boxes is usually the very first location in memory space, which traditionally has been the location of the Interrupt Vector Table (when a hardware or software interrupt hits, that table contains the addresses of the routines that will handle those interrupts). However it's being used now, that part of memory space solidly belongs to the operating systems so accessing it is strengst verboten (most strictly forbidden, but German seems to express the sentiment better). Each process/program is given its own memory space, so then it is imperative that you point that pointer to a location within your own memory space.

    Rolling it by hand in the case of strings, you will need to get the length of the string to be copied, malloc or calloc that string length plus one more for the null-terminator, which marks the end of the string -- always be mindful of the null-terminator. Once you have allocated that memory, then you can call strcpy to copy the string from temp to its destination, such as test->a. Fix that sequence within your mind, because that is what needs to happen.

    In Message #3, b49P23TIvg pointed you to a function, strdup. Read the documentation on that function (eg, Google on man page strdup) and you will see that it automatically calls strlen to get the length of the source string and malloc to allocate space for it and then copies the string to the destination that it had created. It does all that for you automatically, but you still need to understand what it's doing.

    C is both a high-level language and a low-level language, which was written by working programmers to enable them to do everything that they wanted to be able to do. Most C is designed to run on any possible system (and since UNIX was written in C, that is what allowed it to be so easily ported to so many different hardware platforms), yet at the same time it can also access specific memory and hardware-device locations. Even when you write high-level code, as a C programmer you need to always keep in mind what the hardware is doing.

    I hope that I have helped to impart some of that perspective to you in this message.

IMN logo majestic logo threadwatch logo seochat tools logo