C: Getting Segmentation Error -


i have written code input user , save text file.

int main(){     file *fp;     fp = fopen("rahiv.txt", "w");     char s[80];     char a;     gets(s);     = s ;     fputs(s, fp); } 

but if want write fputs part below, it's giving me segmentation error, how can typecast gets() function's return value , fix this!

int main(){     file *fp;     fp = fopen("rahiv.txt", "w");     char s[80];     fputs(gets(s), fp); } 

this unsafe code. i'll try address things in order, , answer question somewhere in process.

1) need make sure file opened successfully. isn't nice java/c#/python/other high level languages it'll throw exception. must check if(fp == null) { /*handle error*/ }

2) trying equate variables a , s, different types , not equivalent. char s[80] allocates array of chars 80 bytes long on stack. looks s of type char, of type char*, line a = s... well, i'm not sure does.

3) gets can return more string. from docs

on success, function returns str. if end-of-file encountered while attempting read character, eof indicator set (feof). if happens before characters read, pointer returned null pointer (and contents of str remain unchanged). if read error occurs, error indicator (ferror) set , null pointer returned (but contents pointed str may have changed).

trying pass return value directly fputs might work if you're lucky , correct, if there error, it'll blow up. in higher level languages, there lot of temptation pass results of method straight parameter of method, in c ends badly because there no try/catch, errors returned special cases of return value. don't try make more compact, favor longer code , put in proper test cases errors!

4) never close file. sure call fclose(fp);, otherwise you'll cause memory leak , possibly undesired behavior if program ever crashes, causing data you've written lost.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -