0

I have gotten this error that has prevented me from continuing my code and testing other parts of the program much at all. The task is to replicate what the nl command does along with the a, n, and t arguments for -b as well as the option to replace the tab normally placed between the number of the line and the line itself with whatever we would like. My code is far from complete but so far the seg fault is hindering me from moving on to test much else and I don't know what else to do.

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#define MAX_LINE_LENGTH 101

void process_stream(FILE *fpntr, char style, char *string);
char *fgetline(FILE *fpntr);


int main(int argc, char *argv[]) 
{
char *string = "\t";
char style = 't';
int opt;


//printf("Hello from main\n");

while((opt = getopt(argc, argv, "b:s:")) != -1)
    switch (opt)
    {
        case 'b':
            style = optarg[0];
            //printf("Hello from case b\n");
            break;
        case 's':
            string = optarg;
            break;
        case '?':
            break;
    }


for(int i=1; i<argc; i++)
    {
        FILE *fpntr = fopen(argv[1], "r");
        //printf("Hello from main for loop\n");
        process_stream(fpntr, style, string);
    }
 return EXIT_SUCCESS;
}


void process_stream(FILE *fpntr,char style,char *string)
{
int cnt = 1;
char *line;

while ((line = fgetline(fpntr)) != NULL)
{
    if(style == 'a')
    printf("%6d%s%s", cnt++, string, line);

    else if(style == 't' && *line != '\n')
    printf("%6d%s%s", cnt++, string, line);

    else if(style == 'n')
    printf("      %s%s", string, line);

}
fclose(fpntr);
}


char *fgetline(FILE *fpntr)
{
static char line_buff[MAX_LINE_LENGTH];
int next, pos = 0;


while((next = fgetc(fpntr)) != EOF && next != '\n')
{
    line_buff[pos++] = next;
}
 line_buff[pos] = '\0';
if(next==EOF && pos == '\0')
return NULL;
else return line_buff;


}
  • 2
    Now is a good time to learn how to use a debugger. – OldProgrammer Feb 25 '18 at 00:44
  • @OldProgrammer How would a debugger help with this? It will confirm that you get a segfault, but won't tell you that the reason is because you tried to return a local array from a function. – Barmar Feb 25 '18 at 00:46
  • Please specify where is the segmentation fault that you are getting. If you don't know exactly where the seg fault is, you can use `fflush(stdout);` after each printf to make sure the `printf()` is executing before the seg fault – chris Feb 25 '18 at 00:47

0 Answers0