1
我試圖從file1.txt
中的id
代碼服務器獲取一些數據。如果我使用字符串文字d.id = "ABC"
,則電話號碼fetchData(&d)
工作得很好,但如果在從文件中讀取它們後使用包含每個id
的變量array[idx]
,則不起作用。任何人都可以給我一個暗示我做錯了什麼(不知道內部的fetchData()
)?我正在學習C,請耐心等待。函數調用使用字符串文字但不帶字符串變量C
的file1.txt
看起來像這樣的內容:
ABC
DEF
...
我的代碼如下:
/* #include "myapi.h" */ //fetchData
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct param {
char *id;
} param_t;
int countlines(char filename[])
{
// count the number of lines in the file called filename
FILE *fp = fopen(filename,"r");
int ch=0;
int lines=0;
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '\n')
{
lines++;
}
}
fclose(fp);
return lines;
}
int main()
{
char filename[] = "file1.txt";
int N = countlines(filename);
// open the file for reading
FILE *file = fopen(filename, "r");
// make sure the file opened properly
if(NULL == file)
{
fprintf(stderr, "Cannot open file: %s\n", filename);
return 1;
}
size_t buffer_size = 10;
/* create an array of char pointers */
char **array = malloc(N * buffer_size * sizeof(char*));
/* allocate space for each string: */
int line_number = 0;
for (line_number = 0; line_number < N; ++line_number) {
array[line_number] = (char *)malloc(buffer_size+1);
}
// read each line into the string array
line_number = 0;
while(-1 != getline(&(array[line_number]), &buffer_size, file))
++line_number;
fclose(file);
param_t d, dempty;
memset(&d, 0, sizeof d);
memset(&dempty, 0, sizeof dempty);
int idx;
for (idx=0; idx<N; idx++)
{
if(!(d.id = malloc(strlen(array[idx]) + 1)))
{
//allocation failed
}
/* if initialized with string literals the data request works */
d.id= "ABC";
/* if d is initialized with a variable the data request doesn't work */
// strcpy(d.id, array[idx]);
fetchData(&d);
/* reset structure*/
d = dempty;
}
/*free memory */
for (;idx>=0;idx--)
free(array[idx]);
free(array);
return 0;
}
編輯:我的問題得到了每個array[idx]
取出\n
字符後解決。
去除
\n
字符考慮發佈您的解決方案作爲回答這樣的問題解決後解決。 –