dtara11
dtara11

Reputation: 11

fwrite keeps writing undesired text into my file

The output text file is only supposed to contain the contents of word1, but other things that are inside of my write function keep getting in there and I'm not sure why.

My main function:

int main(){

unsigned long size4;
char* word1 = "Hellllooooooo";
char* file_namee = "test.txt";
file_write(size4, word1, file_namee);

exit(0); 
}

Here is my file write function:

int file_write(unsigned long size, char *output, char *file_name2){


FILE *file;

file = fopen(file_name2, "wb");
if(file == NULL){
    printf("Cannot open file");
}

fwrite(output, 1, size, file);


fseek(file, 0, SEEK_END);

size = ftell(file);
rewind(file);
return size;
}

Here is what it outputs and writes into test.txt:

Hellllooooooo test.txt rb Cannot open file  wb Cannot 

Everything after "Hellllooooooo" is unexpected and I'm not sure why it's giving me that.

Upvotes: 0

Views: 86

Answers (1)

tadman
tadman

Reputation: 211580

You're using an uninitialized variable. That size parameter is not necessary if you're using C strings. Skip it and:

fwrite(output, strlen(output), 1, file);

fwrite needs to know the length of the buffer which can come in many forms, often raw, so the length parameter cannot be inferred. You must supply it, but as you're using C strings, you can use strlen() to compute.

Upvotes: 2

Related Questions