realloc ()

This is a discussion on realloc () within the C Programming forums, part of the General Programming Boards category; I am trying to to read lines from a file I want to print it using malloc, ....I don't know ...

  1. #1
    Max
    Max is offline
    Registered User Max's Avatar
    Join Date
    Jul 2002
    Posts
    110

    realloc ()

    I am trying to to read lines from a file

    I want to print it using malloc, ....I don't know how long is the text in the file so I want then to increase storage by using realloc()

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main (void)
    {
    	FILE *fptr;
    
    	char fileline;
    	char line;
    
    	fptr=fopen("c:\\c\\file.txt","r");
    
    	line=(char*)malloc(50);
    
    	if(fptr!=0)
    	{
    		while (!feof(fptr))
    			{
                fgets(fileline+strlen(line),50,fptr);
               	}
    	}
    	else
    		{
    		perror("\nError Opening File.\n");
    		}
    	strcpy(line,fptr);
    	puts(line);
    
    	fclose(fptr);
    	free(fileline);
    	
    
    return 0;
    }
    Last edited by Max; 09-25-2002 at 08:46 PM.

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>line=(char*)malloc(50);
    The cast isn't necessary, but you've forgotten to include stdlib.h which has malloc's prototype in it.

    >>while (!feof(fptr))
    Don't use feof() in this manner, its wrong and will give you unexpected results. Search the board for more information.

    >>fgets(fileline+strlen(line),50,fptr);
    Ohhh... nasty! fileline is a char (a single character) and line is new memory, therefore strlen() won't give you want you want.

    >>I want to print it using malloc,
    Clarify please... malloc isn't for printing. What's the purpose of the program?
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. did i understood right this explantion of realloc..
    By transgalactic2 in forum C Programming
    Replies: 3
    Last Post: 10-24-2008, 08:26 AM
  2. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 09:09 PM
  3. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 05:00 PM
  4. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 04:40 PM
  5. Realloc inappropriate for aligned blocks - Alternatives?
    By zeckensack in forum C Programming
    Replies: 2
    Last Post: 03-20-2002, 02:10 PM

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