The code below was written for Linux and uses open, read, write and close. I am working on a Windows computer where I normally use fopen, fgets, fputs, fclose. Right now I get a no prototype error for open, read, write and close. Is there a header file I can include to make this work on a Windows computer or do I need to convert the code? Can you show how to convert it so it works the same on Windows or at least point me to an online document which shows how to convert it?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef unix
#include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#define NB 8192
char buff[NB];
int
main(argc,argv)
int argc;
char **argv;
{
int fdi, fdo, i, n, m;
char *p, *q;
char c;
if( argc > 0 )
printf( "%s: Reverse bytes in 8-byte values \n", argv[0] );
if( argc > 1 )
strcpy( buff, argv[1] );
else
{
printf( "Input file name ? " );
gets( buff );
}
fdi = open( buff, O_BINARY | O_RDONLY, S_IREAD );
if( fdi <= 0 )
{
printf( "Can't open <%s>\n", buff );
exit(2);
}
if( argc > 2 )
strcpy( buff, argv[2] );
else
{
printf( "Output file name ? " );
gets( buff );
}
fdo = open( buff, O_BINARY | O_RDWR | O_CREAT | O_TRUNC,
S_IREAD | S_IWRITE );
if( fdo <= 0 )
{
printf( "Can't open <%s>\n", buff );
exit(2);
}
while( (n = read( fdi, buff, NB )) > 0 )
{
m = n / 8;
p = buff;
q = buff+7;
for( i=0; i<m; i++ )
{
c = *p;
*p++ = *q;
*q-- = c;
c = *p;
*p++ = *q;
*q-- = c;
c = *p;
*p++ = *q;
*q-- = c;
c = *p;
*p++ = *q;
*q-- = c;
p += 4;
q += 12;
}
write( fdo, buff, n );
}
close( fdo );
close( fdi );
exit(0);
}
Borland C++ Builder encapsulated binary file access functions into:
FileOpen
FileCreate
FileRead
FileWrite
FileSeek
FileClose
Here simple example of loading text file:
BYTE *txt=NULL; int hnd=-1,siz=0;
hnd = FileOpen("textfile.txt",fmOpenRead);
if (hnd!=-1)
{
siz=FileSeek(hnd,0,2); // position to end of file (0 bytes from end) and store the offset to siz which means size of file
FileSeek(hnd,0,0); // position to start of file (0 bytes from start)
txt = new BYTE[siz];
FileRead(hnd,txt,siz); // read siz bytes to txt buffer
FileClose(hnd);
}
if (txt!=NULL)
{
// here do your stuff with txt[siz] I save it to another file
hnd = FileCreate("output.txt");
if (hnd!=-1)
{
FileWrite(hnd,txt,siz); // write siz bytes to txt buffer
FileClose(hnd);
}
delete[] txt;
}
IIRC All these are part of VCL so in case you are using console you need to set VCL include check during the project creation or include it manually.