Thread: read a file

  1. #1

    read a file

    I write a small C program to open a file, and read each line of it.
    But how can I remove the "0x0D0A" at the end of each line?
    here is my code:

    while ( fgets(line, MAXCHARS, fp) != NULL)
    printf("line: %s", line);

    Indeed, I want to check each line and compare its value..
    if (line == "my str")


  2. #2
    Registered User
    Join Date
    Jul 2002
    If the string you want to remove is a part of the file and not some corrupted value then you can use strstr() to find and remove it. To compare each string you will need to use strcmp, == will compare the addresses of each string, not the contents.
    if (!strcmp (line, "my str"))

  3. #3
    Hi Crimpy

    Thanks for your reply.

    In my text file, it contains
    hello world
    good morning hello world

    say, if I want to find out the line number which exactly contains the word 'hello', what should I do in this case?

    I tried:
    if (line == "hello")

    but it is not working.
    Using fucntion strcmp would return all the 3 lines

  4. #4
    oh..i got it
    i tried strncmp
    and it works for me..

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    The problem is that fgets() puts the newline character in the array. To remove is, do something like this:

    >if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
    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. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  3. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  4. me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 10:57 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