This blog is under construction

Wednesday, 31 July 2013

C program to convert text file to binary

Write a C program to convert text file to binary file.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
        int num;
        FILE *fp1, *fp2;
        char ch, src[MAX], tgt[MAX];

        /* get the input file name from the user */
        printf("Enter your input file name:");
        scanf("%s", src);

        /* get the output filename from the user */
        printf("Enter your output file name:");
        scanf("%s", tgt);

        /* open the source file in read mode */
        fp1 = fopen(src, "r");

        /* error handling */
        if (!fp1) {
                printf("Unable to open the input file!!\n");
                return 0;
        }

        /* open the target file in binary write mode */
        fp2 = fopen(tgt, "wb");

        /* error handling */
        if (!fp2) {
                printf("Unable to open the output file!!\n");
                return 0;
        }

        /*
         * read data from input file and write
         * the binary form of it in output file
         */
        while (!feof(fp1)) {
                /* reading one byte of data */
                fread(&ch, sizeof(char), 1, fp1);
                /* converting the character to ascii integer value */
                num = ch;
                /* writing 4 byte of data to the output file */
                fwrite(&num, sizeof(int), 1, fp2);
        }

        /* close all opened files */
        fclose(fp1);
        fclose(fp2);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt
  abcdefg1234
  56789hijklm
  123456abcde
  fghijk12345

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name: data.txt
  Enter your output file name: res.bin

  jp@jp-VirtualBox:~/$  vi res.bin
  a^@^@^@b^@^@^@c^@^@^@d^@^@^@e^@^
  a^@^@^@b^@^@^@c^@^@^@d^@^@^@e^@^
  a^@^@^@b^@^@^@c^@^@^@d^@^@^@e^@^






SEE ALSO

    5 comments:

    1. This comment has been removed by the author.

      ReplyDelete
    2. This comment has been removed by the author.

      ReplyDelete
    3. Hi,

      First, I would like to thank you for your good blog.

      I tried your code, it work fine and generate a binary file.

      But, the output file size is bigger then the ascii input file ?
      as I learned, binary file should be smaller.

      Thank you

      ReplyDelete
    4. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. https://onlineconvertfree.com/converter/audio/

      ReplyDelete
    5. Thanks for taking the time to discuss that, I feel strongly about this and so really like getting to know more on this kind of field. Do you mind updating your blog post with additional insight? It should be really useful for all of us. onlineconvertfree

      ReplyDelete