【问题标题】:How to copy text untill newline character?如何复制文本直到换行符?
【发布时间】: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 避免构建错误

标签: c arrays text char


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 好多了,同意。但这仍然会在没有换行符的字符串末尾运行。 :-)
  • @MOehm:根据 OP,“请注意,我确定列表不是空的,并且包含如上所示的文本。”
  • 触摸。我误读了“行为空”,这意味着结果,而不是输入。 (我仍然认为空检查会使代码更普遍地适用于 OP 断言之外。)
  • 是的,就是这样,谢谢。我从其他地方获取了这段代码(并修改了它),所以我认为它会起作用,尽管我自己制作时可能会这样做。再次感谢!
  • @MOehm:同意,添加了空检查。
【解决方案2】:

您也可以使用strcspn() 中的standard library 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2021-04-13
    • 2017-10-04
    • 2021-07-02
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多