Thread: read txt file as binary then convert to text

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    23

    read txt file as binary then convert to text

    read txt file as binary then convert it back to text inside a function? is this possible at all? if so, how?
    fedora 6, gcc 4.1.2

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Huh?
    Linux makes no distinction between "text" and "binary".
    Whether you use fgets() or fread(), it's all just arrays of bytes in the end.

    The only distinction for text files is that isprint() and isspace() are true for the vast majority of the bytes in the file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    As Salem says, a binary file and a text file are essentially the same.
    The main difference are two things:
    1. end-of-line character(s) is/are "translated" from the native representation in the file to the C standard of '\n' when reading a text file, and the other way around when writing.
    2. special character(s) indicating end of file MAY be interpreted as "end of file" in a text-file (typically CTRL-Z), whilst the same character in a binary file is "just another byte".

    In CP/M, DOS, OS/2 and Windows, a "end-of-line" in the file is CR/LF ('\r', '\n'), in Unix/Linux it's LF ('\n'), in older MacOS versions, it's CR ('\r'). Other OS's probably uses a similar scheme, but there are probably other variants too.

    Some OS & Runtime systems don't have a concept of end-of-file character(s), whilst others do - this stems back to the CP/M OS where a file would ALWAYS be a number of 128 byte blocks - so to know the end of a text-file, it requires a special character to indicate the end of the file.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-02-2008, 12:33 PM
  2. Read a text file and respond
    By Arangol in forum C++ Programming
    Replies: 5
    Last Post: 07-12-2006, 04:37 AM
  3. Read in binary file ( pointers )
    By Giant in forum C Programming
    Replies: 41
    Last Post: 06-23-2005, 04:54 AM
  4. How to convert char read from file into string
    By cruxxe in forum C Programming
    Replies: 7
    Last Post: 05-22-2002, 02:09 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM