关于程序:
你好,我正在编写一个简单的程序,从一个.txt文件中提取内容并将其转换为一个.csv文件。计划是在.txt文件中查找特定的单词。这实际上只是为了在linux上用C语言中的函数open()、read()、write()和close()进行实验。
问题是:
在代码的第34行,我尝试存储每个进入的字符以形成一个单词。从.txt中提取“”后,它将清除字缓冲区。
问题是,我得到一个分段错误(核心转储)。我不知道如何解决这个问题。我试着用GDB调试并在34号线发现seg故障。
提前谢谢你
守则

/*
Program to convert content inside a .txt file
into a .csv file.
*/

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>      // open()
#include <unistd.h>     // For read(), write() an close()
#include <string.h>     // Used for strcmp()

int main(int argc, char **argv){

    int samp = open("sample.txt", O_RDONLY);        // This is Opening a file to work with. @param char  *filename,  @param int  access,  @param int  permission
    int csv = open("sample.csv", O_WRONLY | O_CREAT, 0600);     // Used to create a file.

    char *word;         // Stores each word
    char buff[1];       // Holds 1 character of the file
    int i = 0;          // Counter for word buffer

    /* read(handle (file), buffer, size (bytes)) */
    /* write(handle (file), buffer, size (bytes)) */

    while(read(samp, buff, 1) != 0){    // Loops through file, char by char
        printf("%s", buff);             // prints current character in buff

        if(strcmp(buff," ") == 0){      // To create csv, every " " found, we add a ","
            write(csv, ",", 1);         // If " " is found, we write a comma to csv file
            word = "";                  // Clear word buffer
        }

        else{
            write(csv, buff, 1);        // Write value of buff in csv file
            word[i] = buff[0];              // Copy each characer in buff to word
        }

        i++;
    }

    close(samp);    // Closig .txt file
    close(csv);     // Closing .csv file

    return 0;
}

最佳答案

问题在于

 printf("%s", buff);

buff不是字符串。你也可以
buff定义为两个元素数组,char buff[2] = {0};然后将buff用作字符串。
buff定义为单个char(不是数组),将&buff传递给read()调用,并使用%c格式说明符打印buff
使用%c并通过buff[0]
要详细说明,%s格式说明符需要一个参数作为指向以空结尾的char数组的指针。在您的例子中,buff是一个元素太短,无法容纳输入(来自read())和空终止符。因此,由于%s的属性,会发生调用undefined behavior的越界访问。

关于c - 如何使用read()存储单词?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42538885/

10-12 04:44