c - Why am I segfaulting? -
i'm new c, attempting read contents of 1 file character character , output them stream. fopen() command commented out receive segfault (core dumped).
i must run command: ./a.out < testwords.in > myout.txt execute file properly.
here have far:
#include <stdio.h> void main(char *filename[]) { printf("filename %s.\n",filename[0]); //get file based on string inputed file *fp=fopen(filename[0],"r"); //fetches our file read char ch; int linecount = 0; int wordcount = 0; int charcount = 0; //failed find/open file. null character. if (fp == 0) printf("woops! couldn't open file!\n"); //while not @ end of file, grab next char. else while( (ch=fgetc(fp)) != eof) { if (ch == '\n') //on newline { //prints (charcount,wordcount)\n linecount: printf("(%d,%d)%c%d:",charcount,wordcount,ch,linecount); charcount = 0; linecount += 1; } else printf("%c",ch); //mirrors char. } fclose(fp); //closes file (gotta tidy!) }
you can't invent way call main
. need use 1 of standard ways, this:
int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "missing filename\n"); return -1; } file *fp = fopen(argv[1], "r"); // ... }
and note argv[0]
contains program name (if available; if not contains empty string).
your program segfaulted because received int argc
argument char *filename[]
parameter. if ran program single command line parameter, value passed in first argument have been 2, not valid pointer value. expression filename[0]
dereferences address , causes segfault.
Comments
Post a Comment