strcpy - How to copy a single character to string?

This is a discussion on strcpy - How to copy a single character to string? within the C Programming forums, part of the General Programming Boards category; Hi, Lets say I'm reading a certain character from a file stream using the fgetc function. How can I append ...

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    2

    strcpy - How to copy a single character to string?

    Hi,

    Lets say I'm reading a certain character from a file stream using the fgetc function. How can I append this character to another string using the strcopy function (or perhaps a more suitable one from the string.h lib) without running into serious errors?

    Thanks.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,163
    You're probably better off just adding to the string manually rather than calling a function. Something like:
    Code:
    {
      char string[BUFSIZ];
      int index = 0;
      int c;
    
      while((c = fgetc(fp)) != EOF)
        string[index++] = c;
      string[index] = '\0';   /* Mustn't forget to terminate the string */
    }
    That's assuming fp is your file pointer.
    If you understand what you're doing, you're not learning anything.

  3. #3
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    868
    Quote Originally Posted by itsme86
    You're probably better off just adding to the string manually rather than calling a function. Something like:
    Code:
    {
      char string[BUFSIZ];
      int index = 0;
      int c;
    
      while((c = fgetc(fp)) != EOF)
        string[index++] = c;
      string[index] = '\0';   /* Mustn't forget to terminate the string */
    }
    That's assuming fp is your file pointer.
    You'd want to change the while to avoid a buffer overflow, also:
    Code:
    while (index < BUFSIZ-1 && (c = fgetc(fp)) != EOF)

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,163
    True. Good point.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  2. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  4. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21