Tuesday, July 28, 2009

How do u create a file in in C, so that it can be used later on in a program using Linux.?

Linux is written in C, so all you need to do is use a "script" and put it into your library. Just beware that if you customize files that are not native to the OS, and don't add them into the library of your program, it will have portability issues.

How do u create a file in in C, so that it can be used later on in a program using Linux.?
If your file will be ASCII text, about the only thing that might trip up a programme running under linux would be that DOS/Windows applications still have library functions that add a %26lt;cr%26gt;%26lt;nl%26gt; (carriage return/newline) pair of characters at the end of each line. The UNIX 'standard' is to terminate each line only with a newline character, so it is possible that some programmes running on a UNIX machine might pick up and use the carriage return which might yield undesired results.





So, to be safe, you should write your files such that each line is terminated with a newline. Using fopen() to open the file, and fwrite() or fprintf() to write buffers to the file should allow you to do the right thing.





Assuming you have a character buffer that contains a string of text that you want to write to the file, something like this should work and generate a record with just a newline.





fprintf( open_file, "%s\n", buffer );





This is assuming that open_file was declared like





FILE *open_file





and the file was opened like this:





open_file = fopen( "somefile.txt", "w" );





I don't run windows on any of my computers, so I cannot test this for you; I am hoping that the windows C libraries dont add a carriage return as it writes the string. I cannot believe that a library function would alter the data, but I'd not be surprised either.





I seem to remember that under DOS the fopen() function accepted a 'binary' flag. If that option is still there, then you might need to set it to avoid having the library function add a carriage return character to your string.





If you are writing out binary data, then using fopen() and fwrite() should work. Again, that pesky memory of a binary flag is still floating in my head.





An easy check to see if the fwrite/fprintf functions are adding characters would be to build and run this small programme:





#include %26lt;stdio.h%26gt;





int main( )


{


FILE *f;





f = fopen( "test.txt", "w" );


fprintf( f, "hello world\n" );


fclose( f );


}








When you run it, the output file should be 12 bytes long. If the fprintf function is adding a carriage return, then it will be 13 bytes long. If the output is 13 bytes long, then try opening the file as "wb" to see if windows libraries are still using that archane notation. If the 'b' option is supported, then in my opinion you should always use it.





Best of luck!

sweet pea

No comments:

Post a Comment