【发布时间】:2015-03-03 13:42:37
【问题描述】:
我有一个 char 数组 list,其中包含来自文本文件的文本,例如:
this is the first line
this is the second line
我想将第一行复制到另一个不带 \n(和/或 \r)的 char 数组中。
我不知道第一行的确切大小,但我知道它小于 100 字节。
我的代码截图:
unsigned char *line;
line = (u_char *)calloc(100, sizeof(char));
//read txt file to list
while(list[0] != '\n'){
line[0] = list[0];
list++;
line++;
}
不幸的是行是空的。请注意,我确定 list 不为空,并且包含如上所示的文本。
对此代码或其他解决方案有何建议?该文件是使用open() 而不是fopen() 打开的,所以我必须遍历我的列表数组。
【问题讨论】:
-
一个建议是不要改变
line,也就是你引用calloc返回的内存。您是否表明list实际上包含文件中的数据?您可以尝试使用两个数组的索引:for(int n = 0; (n < 100) && (list[n] !='\r') && (list[n] != '\n'); n++){ line[n] = list[n]; } -
@MikeofSST 感谢您的关注,+1 避免构建错误