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
字符考虑发布您的解决方案作为回答这样的问题解决后解决。 –