Thread: File input and appending to a string

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    3

    File input and appending to a string

    I'm reading in a text file. I'm reading it one character at a time. How do I append the char I just read to the end of a string?

    Here is what I've got (the appending part I can't figure out):

    {
    char field[40];
    FILE *stream, *fopen();
    stream = fopen("fisc.txt","r");
    if ( (stream) == NULL)
    {
    printf("Can't open %sn","fisc.txt");
    exit(1);
    }
    else
    {
    char ch;
    int counter;
    counter = 1;
    do
    {
    ch = fgetc(stream);
    //printf("In the else %c\n", ch);
    if (ch != "|")
    {
    field[counter] = ch;
    ++counter;
    printf("%s\n", field);
    }
    }
    while (ch != EOF);

    }
    fclose(stream);
    }

    Any help or suggestions are greatly appreciated.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    There are two ways I can see right off the top of my head. The first will place the character at the end of the array and the second places the character at the end of the current string in the array.
    Code:
    /*Method 1
    **place at the end of the array
    */
    array[SIZE - 1] = ch;
    
    /*Method 2
    **place at the end of the string
    */
    int i = 0;
    while(i < SIZE - 1){
        if(array[i] == '\0'){
            array[i++] = ch;
            array[i] = '\0'; break;
        }else
            i++;
    }
    -Prelude
    Last edited by Prelude; 12-04-2001 at 01:29 PM.
    My best code is written with the delete key.

  3. #3
    Registered User C_Coder's Avatar
    Join Date
    Oct 2001
    Posts
    522
    use a pointer to your string.
    Code:
    while((ch = fgetc(stream) != EOF)
         *field_ptr++ = ch;
    I would use an int for ch as EOF is an integer value.
    All spelling mistakes, syntatical errors and stupid comments are intentional.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. appending text to existing text file
    By kpax in forum C Programming
    Replies: 8
    Last Post: 05-28-2008, 08:46 AM
  2. Help with C Please :)
    By trosty45 in forum C Programming
    Replies: 3
    Last Post: 10-22-2006, 12:39 PM
  3. Input from file no white space characters
    By Dan17 in forum C++ Programming
    Replies: 5
    Last Post: 05-09-2006, 08:28 AM
  4. how to extract words from a string
    By panfilero in forum C Programming
    Replies: 7
    Last Post: 11-04-2005, 08:06 AM
  5. String appending
    By larry in forum C++ Programming
    Replies: 9
    Last Post: 09-30-2001, 04:34 AM