miroki123 miroki123 - 1 year ago 144
C Question

fprintf printing garbage to txt file

I'm having trouble with strings and c.

I'm trying to do something very simple: converting an int into a string and printing it into a txt file in the following fashion.

const char * test_string() {
char s[5];
int num = 123;
sprintf(s, "%d", num);
return s;

int save() {
FILE *fh = fopen("test.txt", "w");
const char * text = test_string();
fprintf(fh, "%s", text);

Yet, for this simple task, I'm getting the following result:


I'd like some assistance with this problem. Thanks in advance.

Answer Source

s is a local variable in test_string, so it is destroyed when test_string returns. Then, you try to print the value of a variable that no longer exists.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download