p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   C++ Programming (http://p2p.wrox.com/c-programming-89/)
-   -   Reading from a text file and writing to a Binary 1 (http://p2p.wrox.com/c-programming/2146-reading-text-file-writing-binary-1-a.html)

scott01 July 28th, 2003 04:59 AM

Reading from a text file and writing to a Binary 1
 
Hi Guys,

I want to write my data read froma text file and write to binary file. Please help!!!!


#include <stdio.h>
#include <stdlib.h>
char * itobs (int n, char * ps);
int invert_end (int num, int bits);
int main (void)
{
    char bin_str[4 * sizeof (int) + 1];
    int number =0;
    char c[10];
    FILE *file;
    FILE *stream;
    file = fopen("numbers1.dat", "r");
    stream = fopen("numbers2.dat", "wb");
    if(file==NULL)
    {
        printf("Error: can't open file.\n");
        return 1;
    }
    else
    {
        printf("File opened successfully.\n");
        while(fgets(c, 16, file)!=NULL)
        {
            number= atoi(c);
            fprintf(stream,"%s", itobs(number, bin_str));
        }
        printf("Now closing file.\n");
        fclose(file);
        fclose(stream);
      }
    return 0;
}
char * itobs(int n, char *ps)
{
    int i; static int size = 4 * sizeof(int);
    for (i = size - 1; i >= 0; i--, n>>= 1)
    ps[i] = (01 & n) + '0';
    ps[size] = '\0';
    return ps;
}



All times are GMT -4. The time now is 08:08 PM.

Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
2013 John Wiley & Sons, Inc.