About the program: Hello, I am writing a simple program to extract content from a .txt file and convert that content into a .csv file. The plan is to look for specific words within that .txt file. This is really just to experiment with the functions open(), read() , write() and close() in C on linux.
The Problem: On line 34 of the code, I try to store each character coming in to form a word. After extracting a " " from the .txt, it will clear the word buffer. Problem is, I get a segmentation fault (core dump). I am not sure how to fix This problem. I tried using GDB to debug and find the seg fault at line 34.
Thank you in advance
The Code
/*
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;
}