user2464820
user2464820

Reputation: 11

Write to file in C

I'm having trouble transferring data from a file to another file using C, and I would like some help from the community to help me troubleshoot some of the output problems. I'm doing this because I want to convert the txt data into binary data next. Totally testing purpose.

Here is the code I have so far:

int txt2txt()
{
    FILE *pTextFile, *pBinaryFile;
    char buffer[1000];
    pTextFile = fopen ("AS001.txt","r");
    pBinaryFile = fopen("BS001.txt","w");
    while(fgets(buffer,1000,pTextFile)!=NULL){
    fwrite(buffer,sizeof(int),sizeof(buffer),pBinaryFile);
}
fclose(pTextFile);
fclose(pBinaryFile);
return 0;
}

Sample input/output:

AS001.txt:

91829812
1231231
1231232
123231123
1232312
123123123
12312312

and output BS001.txt:

91829812
 „w  O]€©O]    * +  O] ¤O]H¨O] ¬O](     O]   @¨O]Lü( ¾8„w8O]š8„w¥ex      O]ˆ©O]  O]8¤O]          ¤O] ¤O]H¨O]`žO]H     O]    8¤O]œü( ¾8„w8O]š8„wuex      O]@¤O]   ЪO]Q      ø    H¨O]PO] ¬O]  O]PO]™Qº€O]PO]  D  Q  Q    ¬O]            Q   ˆ       p¨O] ¬O]Õqˆw¹Qºþÿÿÿ|O]   

Upvotes: 1

Views: 142

Answers (2)

DAhrens
DAhrens

Reputation: 380

Include the string.h from the standard library and change your write command to this:

fwrite(buffer, sizeof(char), strlen(buffer), pBinaryFile);

This will stop it from trying to write the junk data in the rest of the buffer, which is undefined.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 225262

This code:

while(fgets(buffer,1000,pTextFile)!=NULL){
    fwrite(buffer,sizeof(int),sizeof(buffer),pBinaryFile);
}

Tries to read 1000 bytes and then writes 1000 * sizeof(int) bytes per iteration. Unless your system has 1-byte integers (unlikely), that's probably not what you wanted.

Besides that, fgets might not have filled up your entire buffer - it stops at a newline.

Use:

while (fgets(buffer, 1000, pTextFile) != NULL)
{
    fwrite(buffer, 1, strlen(buffer), pBinaryFile);
}

Edit: Since you're having problems, here's a complete example. First, source code:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buffer[1000];
    FILE *pTextFile = fopen("AS001.txt","r");
    FILE *pBinaryFile = fopen("BS001.txt","w");

    while (fgets(buffer, 1000, pTextFile) != NULL)
    {
        fwrite(buffer, 1, strlen(buffer), pBinaryFile);
    }

    fclose(pTextFile);
    fclose(pBinaryFile);

    return 0;
}

Second, build & run:

$ make example
cc     example.c   -o example
$ cat AS001.txt 
91829812
1231231
1231232
123231123
1232312
123123123
12312312

$ ./example 
$ diff AS001.txt BS001.txt 
$ 

Upvotes: 2

Related Questions