开发者

value of char data changes after fwrite [closed]

开发者 https://www.devze.com 2023-01-07 22:53 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

This question does not appear to be about programming within the scope defined in the help center.

Closed 9 years ago.

Improve this question

Hi my code is as follows

char name[100] ;
_getcwd(name, (size_t)sizeOfFileName);
strcat(name,"\\") ;
strcat(name, fileName) ;
char *value_str= NULL ;
file = fopen(name, "a+");
if(!file)
   printf("bad file name") ;
for(i = 0; i<fileSize ; i++)
 {
  value_str = fp_to_str(ddata[i]) ;
  strLength= strlen(value_str) ;
  value_str[strLength+1] = 10 ;
  num = strlen(value_str);
  count = fwrite(value_str, sizeof(char), num, file);
 }

I'm having problems writing the value of value_str into the file given by file. Until it reaches the line of 开发者_开发技巧code containing fwrite, the value of value_str does not change. then it changes to some junk value. Can you please tell me what is wrong? SizeOfFileName is passed to the function earlier. the code works perfectly until it reaches the fwrite line of code and then its value just changes. and some junk values are written into the text file.

the function fp_to_str is my own function in the current code. it properly returns the value i want to value_str. what fp_to_str does is to convert a double number into a character array, which is stored in value_str.

once the code is done with the fwrite, it changes the correct data that is there in value_str to some garbage value.

ddata[i] takes the double number from the double array one by one and passes it into fp_to_str(). what i am trying to do is write these double numbers which are in ddata[] array into a text file.

I have commented the line to add value 10 to the end of the string. I assumed wrongly that I have to add a null character at the end of the string. I still am having the same problem. anyone know why?


In addition to what Adrian McCarthy said:

value_str = fp_to_str(ddata[i]) ;
strLength= strlen(value_str) ;
value_str[strLength+1] = 10 ;
num = strlen(value_str);

num will be equal to strLength here, which makes me think you're not sure as to what you're doing. (What are you doing?) You've add the value 10 (Magic constant - is this a newline? Use '\n') to the space after the null terminator. Your string is:

o  W  o  r  l  d  \0 \x10


If value_str does not change until the line containing fwrite, then fp_to_str must be returning NULL (since the pointer was initialized to NULL and you report that that value doesn't change). Is NULL a valid return value from fp_to_str, or might that indicate an error?

0

精彩评论

暂无评论...
验证码 换一张
取 消