Thread: manipulating fgetc while reading a file

  1. #1
    Registered User
    Join Date
    Dec 2007

    manipulating fgetc while reading a file

    i am writing code that basically reads in a text file and only reads in code up to a certain character. It's a simple assembler that needs to read in assembly code whilst discarding comments that follow after '#' sign. For example code line like this:
    addi  $3,$0,40   # j  = 40
    needs to be read in like this:
     addi  $3,$0,40
    and here is my code so far:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #define LEN 50
    static FILE *open_file (char *file, char *mode) 
      FILE *fptr = fopen (file, mode); 
      if (fptr == NULL){			
        perror ("Unable to open file");	/* if file is not found prints error message */
        exit (EXIT_FAILURE);
      return fptr;	/* returns a  pointer */
    int main (int argc, char *argv[])
        int array_pos = 0, array_elem;
        char letter, word[LEN];
        FILE *fptr;
        fptr = open_file (argv[1], "r");
            letter = fgetc (fptr);
            if (letter != '#')
                word[array_pos] = letter;
                word[array_pos] = '\0';
                word[array_pos + 1] = '\n';
                array_pos = 0;
                printf ("%s\n", word);
        } while (letter != EOF);
        fclose (fptr);
        //printf ("%s\n", word);
        return 0;
    So I want it to read in everything up to the "#' and then go to new line. I have a small amount of experience using fgetc, but I thought if after it reads stuff I want it to read in, I simply put '\0' to indicate end of string and then put in '\n' to make it go to the next line, but I cant get it to work. What do I do to make it ignore any text after '#' ?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Once you detect a #, you still need to read the rest of the line in order to throw it away (up to a \n character). Also, I would think you would want the \n before the \0 in your output, otherwise the \n will never get printed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
Website Security Test