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

How to copy text untill newline character?

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

this is the first line
this is the second line

我想将第一行复制到另一个不带 \n (and/or \r) 的字符数组。

我不知道第一行的确切大小,但我知道它少于 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++;
}

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

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

你可以这样做:

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

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

Declaration:

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

Finds the first sequence of characters in the string str1 that does not contain any character specified in str2.

Returns the length of this first sequence of characters found that do not match with 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);