![]() |
| | #1 |
| Registered User Join Date: Aug 2008
Posts: 15
| Text File Handling - seg fault It takes the input but doesnt print DONE.. Plz help me out... Code: #include <stdio.h>
main() {
char * ptr;
printf("\nName the file: ");
scanf("%s",ptr);
FILE *f=fopen(ptr,"a");
if(f) {
fprintf(f,"The file is appended here\n");
fclose(f);
}
printf("\nDONE!\n");
}
Last edited by Salem; 08-24-2008 at 10:12 AM. Reason: Code is not written in italics |
| nishkarsh is offline | |
| | #2 |
| and the hat of vanishing Join Date: Aug 2001 Location: The edge of the known universe
Posts: 21,214
| ptr isn't allocated any space, so when you read in your string it goes to a random place in memory. In your case, in this instance, it blows up. Allocate some space, or just use a char array. > FILE *f=fopen(ptr,"a"); Mixing declarations and statements is not allowed in regular C Also, be specific about main returning int, and actually return something.
__________________ If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut. Up to 8Mb PlusNet broadband from only £5.99 a month! |
| Salem is offline | |
| | #3 |
| Registered User Join Date: Aug 2008
Posts: 15
| Thx for your reply... I've made the changes u suggested... but the prob still persists... the modified code is; Code: #include <stdio.h>
int main() {
char name[20];
printf("\nName the file: ");
scanf("%s",name);
FILE *f;
f=fopen(name,"a");
if(f) {
fprintf(f,"The file is appended here\n");
fclose(f);
}
printf("\nDONE!\n");
return 0;
}
|
| nishkarsh is offline | |
| | #4 | |
| Registered User Join Date: Jan 2008
Posts: 276
| Quote:
Also, I don't have any problems compiling and running your code. Are you sure you aren't trying to enter a filename that's too large for the buffer? | |
| arpsmack is offline | |
| | #5 |
| Registered User Join Date: Aug 2008
Posts: 15
| its working now thanks ppl |
| nishkarsh is offline | |
![]() |
| Tags |
| append, file, segmentation, text |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Basic text file encoder | Abda92 | C Programming | 15 | 05-22-2007 01:19 PM |
| Post... | maxorator | C++ Programming | 12 | 10-11-2005 08:39 AM |
| Dikumud | maxorator | C++ Programming | 1 | 10-01-2005 06:39 AM |
| Batch file programming | year2038bug | Tech Board | 10 | 09-05-2005 03:30 PM |
| Ok, Structs, I need help I am not familiar with them | incognito | C++ Programming | 7 | 06-29-2002 09:45 PM |