View Single Post
  #1 (permalink)  
Old July 28th, 2003, 03:59 AM
scott01 scott01 is offline
Registered User
 
Join Date: Jul 2003
Location: , , .
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default 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;
}