fopen ("file", "wb") still writes cf-lf text files in VS2005

    Question by:


    Using Visual Studio 2005 in pure C (no C++) I have problems with writing a binary file using fopen() and fputc(). Here is my little test program:

    int main (int argc, char* argv[])
          FILE *fp;
          fp = fopen ("crlf.tmp", "wb");
          fwrite ("abc\n", 1, 4, fp);
          fputc ('x', fp);
          fputc ('y', fp);
          fputc ('z', fp);
          fputc ('\n', fp);
          fclose (fp);
          return 0;

    When you look at the resulting file in a hex editor, in both cases the linefeeds are translated into a CR-LF pair. Which would be OK if the file was opened as default or as a text-file but not when it is opened in binary mode.

    This has for me been an ongoing problem. Last time I circumvented it by replacing my C-style file I/O with MS specific calls like CreateFile() and  ReadFile(). But this time I prefer to solve the problem "once and for all". :) Also I need this code to be platform independent and this problem doesn't occur on my Unix systems.

    Good Question?

    Verified Answer?

    The member who asked this question verified this comment provided the solution that solved their problem.

    by:Posted on 2007-08-07 at 20:44:37ID: 19651302

    I ran the same code in a cpp win32 console project, no compile errors and it generated a the file without any CR only the LF character.

    What hex tool did you use to see if there are any CR's  in the file? The resulting filesize is 8 bytes. What do you see as the filesize? (6 bytes for the printable ascii and two newlines).

    This content is available to Experts Exchange members

    See the answer now
    with your Free 30 Day Trial

    Get unlimited access to solutions & experts

    • 4,169,477 solved questions
    • 3,805 articles & videos
    • 15,413 tech experts

    Get Access Now

    Ask Your Tech Question. Get Expert Solutions.We will email you when an expert has commented on your question.

    We will never share this with anyone.

    Select topics

    You may select up to five topics.

    Top Expert Contributor

    Essential articles and videos from the Experts

    More valuable questions with Expert answers


    RELATED TOPICS view all topics

    1. ASP.NET
    2. C#
    3. Visual Basic.NET
    4. MS Development
    5. Editors IDEs
    6. Visual Basic Classic
    7. MS SQL Server
    8. MS SQL Server 2005
    9. Programming
    10. JavaScript