Thread: Reading Strings from Buffer

  1. #1
    Registered User Mcdom34's Avatar
    Join Date
    Jun 2012
    Location
    North Royalton, Ohio, United States
    Posts
    22

    Reading Strings from Buffer

    I'm writing a program that reads strings from a character buffer, and then prints a confirmation. The buffer I have initialized has a size of 50, but the number of strings inside the buffer isn't necessarily going to be 50. I am stuck on stopping the read once every string has been processed.

    Code:
    if((pid2=fork())==0){
    		int i, bytes; close(bc[1]);
    		for(i=0;i<sizeof(msg);i++){
    			if(strstr(msg, " ")!=NULL)
    				break;
    			else{
    				bytes = read(bc[0], msg, 3); 
    				printf("C received %s from B\n", msg);
    				sleep(1);
    			} 
    		} 
    		close(bc[0]); exit(1);
    I've tried looking for a white space, then breaking, but that hasn't worked. Any suggestions?

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    can you give a better description of what your input file looks like? exactly? and what the output should look like?
    I see you are reading 3 bytes at a time from bc[0]. does that mean each part of your message is 3 characters long? are you sure the file has blanks in it after your strings?

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You need to check the return value of read to make sure you actually got data (i.e. it didn't get EOF or error). Then, if you want to use strstr, you need to null terminate msg, or you need to do as oogabooga suggested in your other thread, and use memchr.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading into & from a buffer
    By Tropod in forum C++ Programming
    Replies: 4
    Last Post: 10-20-2009, 05:51 PM
  2. Reading input buffer
    By Sparrowhawk in forum C++ Programming
    Replies: 0
    Last Post: 02-23-2009, 04:17 PM
  3. Extracting strings from a buffer
    By MoonSire in forum C Programming
    Replies: 11
    Last Post: 07-31-2006, 02:16 AM
  4. EOF reading in the buffer
    By SuperNewbie in forum Windows Programming
    Replies: 1
    Last Post: 12-17-2003, 07:07 AM
  5. Replies: 13
    Last Post: 04-11-2002, 08:46 AM