我正在尝试从字符串(char *)中逐行读取。我试图根据我在网上阅读的内容来实现它,但它不起作用。我编写了此测试代码以使其在我的项目代码之外工作,但它仍然无法正常工作(第一次 readline 调用时出现段错误)。
提前感谢您的帮助!
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
static void parse_message(char *message);
static void readline(char *message, char *line, int *counter);
int main(int argc, char *argv[]){
printf("starting\n");
char *message1 = "Chat {\nHey what's up do you like zebras?\n}\n";
parse_message(message1);
printf("Finished\n");
return EXIT_SUCCESS;
}
static void parse_message(char *message){
char *line = (char *) malloc (50 * sizeof(char));
int *counter = 0;
readline(message, line, counter);//read in first line
if(strcmp(line, "CHAT {") == 0){
readline(message, line, counter); //read in message
printf("%s",message); //print message
readline(message,line,counter); //read in close bracket
} else{
printf("Error occurred\n");
}
}
static void readline(char *message, char *line, int *counter){
int index = 0;
while(message[*counter] != '\n'){
line[index] = message[*counter];
counter++;
index ++;
}
}