Write File byte[] array received from C# to a file in C dll

I just created a simple PDF Document containing a word "Test" in it and created a byte stream out of it in C# Console Application:

buff = File.ReadAllBytes(<Path of File>);

The size of the file is around 9,651 bytes. I also created a Win32 C dll that exports a function which takes the file byte array and the length of the byte array as an argument, declared in C# using this:

[DllImport("<path to dll>", CallingConvention = CallingConvention.Cdecl)] public static extern int file_data(byte[] byteArray, int length);

The method in C dll is exported as below:

#define FILEDATA_API __declspec(dllexport) FILEDATA_API int file_data(char *byteArray, int size);

I then invoked ret = file_data(buff, buff.length); and in the C code, wrote the character pointer received directly to a temp file character by character as below:

    while (length> 0)
        fprintf(outFile, "%c", *fileData); //fileData is the actual byte array received from C# Code

But the problem arises here, the C code that dumps out the byte array to a file character by character generates a file of size 9,755 bytes. Most of the content inside it seems to look correct, except some new lines that gets introduced(as far as i know and may be some additional data), which causes the PDF file to get corrupted and this dumped out version does not open in Adobe. Can someone please provide some pointers on where I might be going wrong? I cannot use %s in fprint since some combination of the byte array in the PDF results in null terminated string in C which then dumps out even lesser data than I expect.



  1. The desired behavior is that the file byte array as received from C# and when written using C code to a file should make the file open successfully in Adobe.
  2. The code present in the problem should be sufficient for someone to generate a win32 dll, that simply writes out the char pointer to a file, but I have added few more details.


You're probably calling fopen without the b mode flag. Append b to your mode specifier:

FILE *outFile = fopen("file.txt", "wb")

From this site (emphasis mine):

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

In my experience, this "conversion" on Windows changes \n to \r\n at least.

Need Your Help

Text formatting within textarea

html formatting tags textarea

Variations on my problem have been discussed elsewhere, so I hope I'm not duplicating!