Thread: Little bit of help please

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    16

    Little bit of help please

    I am writing a program which reads in strings from a file in.txt and then converts it to html friendly text and outputs it to out.txt. When I try to run it I get a segmentation fault, so I am not sure what I am doing wrong.

    Also, as you will see in my switch statement I have to convert the " ' " character to "&apos", but I don't know how to write " ' " in c.

    Here is my code:

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<ctype.h>
    #include<stdbool.h>
    
    int main()
    {
      FILE *in;
      FILE *out = NULL;
    
      in = fopen("in.txt", "r");
      if(in == NULL)
      {
        perror("Unable to open in.txt");
    	return 1;
      }
      
      out = fopen("out.txt", "w");
      if(in == NULL)
      {
        fclose(in);
        perror("Unable to open out.txt");
        return 1;
      }
    
      char line[100];
      int i;
      while (fgets(&line[i], 100, in) != NULL)
      {
        for(i=0; i!= '\0' && i<100; ++i)
    	{
    	  switch (line[i])
    	  {
    	    case '"':
    		fputs("&quot", out);
    		break;
    		
    		case 'd':
    		fputs("&apos", out);
    		break;
    		
    		case '&':
    		fputs("&amp", out);
    		break;
    		
    		case '<':
    		fputs("&lt", out);
    		break;
    		
    		case '>':
    		fputs("&gt", out);
    		break;
    		
    		default:
    		fputc(line[i], out);
    		break;
    	  }
    	}
      }
      
      fclose(out);
      fclose(in);
    }

    Also here is the sample in.txt we are suppose to convert:

    This is some text.
    <TAG>
    "Double Quote Line"
    'single quote line'
    An ampersand: &
    </TAG>
    End of file.


    Thanks in advance for all the help!

  2. #2
    Registered User
    Join Date
    Oct 2010
    Posts
    16
    I currently just put 'd' in the &apos spot because I wanted to see if it would compile and run

  3. #3
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    Try:
    Code:
    '\''
    Escape Sequences
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  4. #4
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    Quote Originally Posted by mytrademark View Post
    Code:
      char line[100];
      int i;
      while (fgets(&line[i], 100, in) != NULL)
      {
        for(i=0; i!= '\0' && i<100; ++i)
    	{
    	  switch (line[i])
    	  {
    Oh my god, please read a good C book.
    Try:
    Code:
      char line[100];
      int i;
      while (fgets(line, 100, in) != NULL)
      {
        for(i=0; line[i]!='\0'; ++i)
    	{
    	  switch (line[i])
    	  {

  5. #5
    Registered User
    Join Date
    Oct 2010
    Posts
    16
    Thank you both so much. Works perfectly now!

Popular pages Recent additions subscribe to a feed