Reading string from a file

This is a discussion on Reading string from a file within the C Programming forums, part of the General Programming Boards category; I have been trying to read a string input from a text file. In the code below, I open a ...

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    2

    Question Reading string from a file

    I have been trying to read a string input from a text file. In the code below, I open a file and assign it to FILE * stream. The file passed by argv[1] contains text file. I am trying to figure out a way how I can read the string contents stored into the buffer (curbuff) and then tokenize the string. I guess I can use strtok() to chop the string but I am not sure how would I extract the string out of the buffer. Any help would be appreciated.
    ------------------------------------------------------------------------
    Code:
            int cnt;
    	node *nodes;
    	int num_nodes = 0;
    	char curbuff[50];
     
    	FILE *stream = fopen(argv[1],"r");
    
    		if(stream == NULL)
    			perror("Invalid Input");
    	
    		else{ 
        		  
    			while(!(feof(stream))){
    			fgets(curbuff,545,stream);
    			printf("line: %s",curbuff);		
        		
    				if (num_nodes == 0){
                                nodes = calloc(1,sizeof(node_t));		
    				}	
    				else{
                    nodes = realloc(humans,num_nodes+1)*sizeof(node_t));					
    				}

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You are telling fgets to read 545 bytes but curbuff only has 50 available.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 05:27 PM
  2. disposing error
    By dropper166 in forum C# Programming
    Replies: 2
    Last Post: 03-31-2009, 12:53 AM
  3. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 05:30 PM
  4. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 10:11 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM

Tags for this Thread


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