read a file

This is a discussion on read a file within the C Programming forums, part of the General Programming Boards category; Hello, I write a small C program to open a file, and read each line of it. But how can ...

  1. #1
    Unregistered
    Guest

    read a file

    Hello,
    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..
    eg.
    if (line == "my str")
    ...


    Thanks

  2. #2
    Registered User
    Join Date
    Jul 2002
    Posts
    66
    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.
    Code:
    if (!strcmp (line, "my str"))

  3. #3
    Unregistered
    Guest
    Hi Crimpy

    Thanks for your reply.

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

    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
    Unregistered
    Guest
    oh..i got it
    i tried strncmp
    and it works for me..
    hehe

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    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. Hmm....help me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 09:57 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 01:58 AM

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