简体   繁体   English

在 c 中使用 strsep 函数需要帮助

[英]Need help using the strsep function in c

int main(int argc, char *argv[])    
 {
    char *line, buffer[1024];
    char *token, *setValue, *pointer;


    FILE *fp = fopen("file", "r");
    if(fp == NULL)
    {
        printf("File was unable to be opened.\n");

    }

     fgets(buffer,1024,fp);  
      printf("%s\n", buffer);
     while(fgets(buffer,1024,fp) != NULL)
  {
    strcpy(token, strsep(&buffer, ","));
    printf("%s\n", token);
  }



 return 0;
 }

I'm having a bit of trouble understanding how strsep works.. I've looked up tutorials for it, but when I try different methods, it keeps just not being able to compile.. It'd be appreciated if someone helped me understand the syntax and the way it works.我在理解 strsep 的工作原理时遇到了一些麻烦.. 我已经查找了它的教程,但是当我尝试不同的方法时,它一直无法编译.. 如果有人帮助我理解,我将不胜感激语法及其工作方式。 Thank you.谢谢你。

**EDIT: 'Buffer' contains "I,was,in,the,school" **编辑:“缓冲区”包含“我,曾经,在,学校,学校”

****EDIT x2: I'm trying to parse a csv file, and using the basic 'Buffer' I created on my desktop as an example. ****编辑 x2:我正在尝试解析一个 csv 文件,并以我在桌面上创建的基本“缓冲区”为例。 I want to separate the different words by the respective comma.我想用相应的逗号分隔不同的单词。

regarding:关于:

strcpy(token, strsep(&buffer, ","));

the variable token is ONLY a pointer, it has not been set to point to any memory that the application owns.变量token只是一个指针,它没有被设置为指向应用程序拥有的任何内存。 Therefore, it will contain what ever trash was on the stack at the location of the variable.因此,它将包含堆栈中变量位置的垃圾。

The result is undefined behavior and it can lead to a seg fault event.结果是未定义的行为,并且可能导致段错误事件。

Suggest declare token as建议将token声明为

char token[ 1024 ];

so it is large enough to hold a maximum length string (IE the length of buffer[]所以它足以容纳最大长度的字符串(即buffer[]的长度buffer[]

as it the above wasn't bad enough:因为上面还不够糟糕:

the posted code is missing the statement: #include <string.h> so as to expose the prototype for the function strsep() so the compiler will make the assumption that the parameters and returned value are int rather than their actual types.发布的代码缺少语句: #include <string.h>以便公开函数strsep()的原型,因此编译器将假设参数和返回值是int而不是它们的实际类型。

The posted code is also missing the statement: #include <stdio.h> so the parameter and return types for the functions: fopen() , fgets() , printf() and even the struct type for FILE are assumed to be int` rather than their actual types.发布的代码也缺少语句: #include <stdio.h>因此函数的参数和返回类型: fopen()fgets() 、 printf() and even the struct type for FILE and even the struct type for are assumed to be int`而不是它们的实际类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM