Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a global string variable, set it somewhere, and fputs it to a file?

Tags:

c

syntax

I'm new to the C language although I hear its very similar to c++ since c++ is kind of an add on to C?

I can't seem to get a global variable (empty string) to be set in a method and then printed to a text file.

I've tried a few things, but based on what seems to make sense and worked for me in other parts of my program.. this is where I'm at:

char fileReqName[1024] = "";//trying to create the global variable
//code lines and methods
//theres a pointer that point's to a "token" thats a string.. called pptr
strncpy(fileReqName, pptr, sizeof(pptr));

//in another method:
fputs(fileReqName,file_ptr);

But it's not working.

It's supposed to be getting a "filename" from a browser request. Sometimes it's cutting the name of the file the browser goes to into a smaller string and sometimes its not displaying anything. It could be a problem with the token, but when I was displaying it before, the token was always correct.

I also just tried:

strcpy(fileReqName, pptr);

which seems to work sometimes as well haha. I think I might have to check the other code for why it's not displaying the correct string/path?

Any suggestions? Thanks

like image 914
Habit Avatar asked Jan 27 '26 13:01

Habit


1 Answers

If pptr is a pointer, sizeof(pptr) is probably 4 bytes. That would copy 4 bytes into fileReqName. You need to copy the length of the string, not just sizeof(pptr) (something like strlen(pptr)).

like image 146
edtheprogrammerguy Avatar answered Jan 29 '26 05:01

edtheprogrammerguy