0

I am having a problem while trying to print to txt file from global array of char*.

My array is declared as

char* codes[256];

also i have a function that construct a string and returns it to after which that value is placed into this global array

char* printArr(int arr[], int n)
{

    char* code = (char *) malloc(sizeof(char) * (n+1));

    int i;
    for (i = 0; i < n; ++i)
    {
        code[i] = arr[i] + '0';
    }
    code[n] = '\0';

    return code;
}

after which I just simply place that value into that global array. After that I am trying to print that array values into a txt file like this :

void PrintToFile(char* outputFileName)
{

   FILE* f = fopen(outputFileName, "w+");

   int i;

   for (i = 0; i < 256; ++i)
   {
        //printf("%s\n", codes[i]);
        fprintf(f, "%s\n", codes[i]);
   }

   fclose(f);
}

But for some reason my txt file turns out blank. Also without opened stream when I try to print to stdout i get those values but with both printf and fprintf I don't get anything out either on stdout or in txt file.

Thanks in advance!

mpisacic
  • 11
  • 3
  • [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Jan 04 '17 at 15:14
  • did it a number of times before without any problems and I don't think that is the problem here but thanks anyway – mpisacic Jan 04 '17 at 15:15
  • Is the attempt to open the file working? Try just printing a string literal test text to it. – Malcolm McLean Jan 04 '17 at 15:19
  • nothins is printed out, even if i put fprintf(f, "%s\n", "test") and loop it 256 times still got empty – mpisacic Jan 04 '17 at 15:22
  • "Empty" as in zero bytes long, or "empty" as in "my text editor doesn't display any printable characters"? – John Bollinger Jan 04 '17 at 15:23
  • file is zero bytes – mpisacic Jan 04 '17 at 15:24
  • You've not given us enough to work with here. We ordinarily expect a [mcve] demonstrating the problem. – John Bollinger Jan 04 '17 at 15:26
  • don't know what more is it here to give everything else is working fine if you print to stdout you get data but can't print anything to file – mpisacic Jan 04 '17 at 15:27
  • We don't want "everything else". We want minimal code to make a complete program that demonstrates the problem, and any input needed to cause the program to do so -- hence *complete* and *verifiable*. Although this may contain excerpts of your program, such as the pieces you've already provided, it will not ordinarily be a subset of your program's code, as that typically is not *minimal*. Follow the link in my previous comment if you require further clarification. – John Bollinger Jan 04 '17 at 15:34

0 Answers0