如何复制文本直到换行符?

时间:2015-03-03 13:42:38

标签: c arrays text char

我有一个char数组list,其中包含文本文件中的文本,例如:

this is the first line
this is the second line

我希望将第一行复制到另一个没有\ n(和/或\ r \ n)的char数组。

我完全不知道第一行的大小,但我知道它不到100个字节。

我的代码的Snappet:

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++;
}

不幸的是空行。请注意,我确定列表不是空的,并且包含如上所示的文本。

对此代码或其他解决方案的任何建议?该文件是使用open()而不是fopen()打开的,因此我可以遍历我的列表数组。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

for ( int i = 0; list[i] && list[i] != '\n'; ++i ) {
    line[i] = list[i];
}

答案 1 :(得分:1)

您还可以使用standard library strcspn()中的string.h

  

声明:

size_t strcspn(const char *str1, const char *str2); 
     

查找字符串str1中的第一个字符序列   不包含str2中指定的任何字符。

     

返回找到的第一个字符序列的长度   与str2不匹配。   Source

您的程序将成为

unsigned char *line;
int firstlineLength;

//read txt file to list

/*count the characters up to first linebreak */
firstlineLength = strspn(list, "\n"); 
/* allocate just the memory you need +1 one for the terminating zero*/
line = (u_char *)calloc(firstlineLength+1, sizeof(char));
strncpy(line, list, firstlineLength);