Thread: Simple C App to add line breaks to a text file

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

    Simple C App to add line breaks to a text file

    Hi all,

    I am a quite inexperienced C programmer and am trying to write a simple program to add HTML line breaks to a text file. I actually got the program to compile but it gives me weird output.

    for example:

    Original file:
    Code:
    Hello World of C Programming.
    Altered File:
    Code:
    (×û¿žÌ
    žô·aƒ ProHž@+
    ž<br />
    Here is my source code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char buffer1[500];
    
    char* readLine(FILE *fp) 
    {
    	int tc, cnt = 0;	
    	char tmp;
    	while ((tc = fgetc(fp)) != -1)
    	{
    		tmp = (char) tc;
    		if (tmp == '\n')
    		{
    			return buffer1;
    		}
    		else 
    		{
    			buffer1[cnt++] = tmp;
    		}
    	}
    	return NULL;
    }
    
    int main(int argc, char **argv)
    {
    	FILE *fl;
    	char *tmp = malloc(sizeof(char) * 500);
    	char file[50], buffer[5000] = "";
    	printf("Enter the name of the file you wish to affect> ");
    	scanf("%s", file);
    	fl = fopen(file, "r");
    	while ((tmp = readLine(fl)) != NULL)
    	{
    		strcat(buffer, tmp);
    		strcat(buffer, "<br /> \n");
    	}
    	fclose(fl);
    	fl = fopen(file, "w");
    	fprintf(fl, buffer);
    	fclose(fl);
    	printf("Your file has been altered thanks for using webliner\n");
    	free(tmp);
    	return 0;
    }
    In my mind it is probably a simple little bug but I cant find it.

    All help is greatly appreciated.
    Last edited by sari; 07-09-2009 at 11:10 PM.

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    readLine() is returning the address of a local variable.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Jul 2009
    Posts
    2
    Ok thank you all i did was rename the buffer in readLine() to buffer1 and made buffer1 an external string thanks again
    Last edited by sari; 07-09-2009 at 11:08 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  3. printing out a line from text file..
    By loso44x in forum C Programming
    Replies: 3
    Last Post: 10-22-2005, 01:14 PM
  4. Ok, Structs, I need help I am not familiar with them
    By incognito in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2002, 09:45 PM
  5. Greenhand want help!
    By leereg in forum C Programming
    Replies: 6
    Last Post: 01-29-2002, 06:04 AM