我正在嘗試從文本文件中讀取數據&將其存儲在具有一個char指針的結構中& int變量。 從文件中獲取數據期間,我知道將有一個字符串來獲取一個整數值。 我也知道位置表單,我必須開始提取。 我不知道的是字符串的大小。 那麼,我該如何爲該String分配內存。 示例代碼是在這裏:在您的幫助如何動態地爲字符串分配內存?
struct filevalue
{
char *string;
int integer;
} value;
fseek(ptr,18,SEEK_SET);//seeking from start of file to position from where I get String
fscanf(ptr,"%s",value.string);//ptr is file pointer
fseek(ptr,21,SEEK_CUR);//Now seeking from current position
fscanf(ptr,"%d",value.integer);
感謝。
家庭作業,對吧? – 2012-06-01 07:03:45
不能工作的人只能工作 – tod
您需要知道所需的長度,然後使用'malloc()'並記住爲空終止符添加一個。 – hmjd