How do I store repeated null characters in a string in C from fgetc?

Viewed 65

EDIT: This simply doesn't work reliably with strings. I have changed the entire system to work with int arrays. Eliminated a bunch of other headaches, too. The working version of my MVC is:

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

int main (){
    int nextChar;
    int augmented[256];
    int index = 0;
    while ((nextChar = fgetc(stdin)) != EOF){
        augmented[index] = nextChar;
        index++;
    }
    for (int i = 0; i <= index;++i){
        printf("%c", augmented[i]);
    }
}

END EDIT

ORIGINAL POST:

I am trying to implement an LZW compressor for an assignment. So far, everything works great on text, but I am putting out garbage if the input file contains a long run of null characters.

Right at the start I store the incoming char as an int to check for EOF and then cast it to a char to concat to my augmented string for dictionary comparison. I have printed out my dictionary after each file and find that with long runs of zeros my dictionary entry is a null string.

I think that whats happening is that it takes a string of zeros and makes it a single zero. Not the desired value. I need to put out ALL those zeros.

I have made a minimal viable code to show the error and have found that it occurs right at the casting stage. How can I build a check for the null character so that I can substitute it for something else that can be stored in a string?

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

int main (){
    int nextChar;
    char augmented[256] = "\0";
    while ((nextChar = fgetc(stdin) != EOF)){
        char charBuffer[2];
        sprintf(charBuffer, "%c", nextChar);
        strcat(augmented, charBuffer);
    }
    printf("%s",augmented);
}

I've been searching for a couple days and I guess I can't seem to figure out what the correct query should be as I'm not finding any useful results.

2 Answers

here are some updates to your program. 0's are converted to '0's. Not exactly sure what you're looking for but hopefully this gets you pointed in the right direction:

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

int main (){
    int nextChar;
    char augmented[256] = {0}; // zero entire array
    int i = 0;
    while ((nextChar = fgetc(stdin)) != EOF){
        // convert 0 to some other character
        if( nextChar == 0 ) nextChar = '0';
        augmented[i++] = (char)nextChar;
        //check for buffer overflow
        if( i==255) break;
    }
    printf("%s",augmented);
}

The problem is parenthesis. Change to:

while ((nextChar = fgetc(stdin)) != EOF){

Your code assigned the value of the comparison fgetc(stdin)) != EOF to nextChar.

And you should also initialize charBuffer to zero.

Related