Reading a Line from stdin in C
Jul 1, 2018 at 6:14am UTC
Hey all,
Making a guitar tab template writer, and wanted user to be able to set the name of the file written out. Getting a core dump on marked lines in function nameOfFile(Tab* tab). Not sure why. Why am I getting the core dump, and how might it be resolved?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
/* PROJECT: tabWriter
Author: |||||||||||||
Version: 2.0 21 Jun 18 Variable length tab complete
3.0 30 Jun 18 Adding file name detection
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char * tabStr;
int songLen;
char * fileName;
FILE* fp;
} Tab;
void nameOfFile(Tab* tab) {
printf("Name of file >> " );
// fgets(tab->fileName, 32, stdin); // core dump prior to here if uncommented
scanf("%s" , tab->fileName); // core dump here
printf("Writing: %s" , tab->fileName);
}
int allocateTab() {
int songLen;
printf("Enter song length >> " );
scanf("%d" , &songLen);
return songLen;
}
void makeTab(Tab* tab) {
int i;
i = 1;
tab->tabStr[0] = '<' ;
for (i = 1; i < tab->songLen - 2; i++)
tab->tabStr[i] = '-' ;
tab->tabStr[tab->songLen - 2] = '>' ;
}
int numOfRows() {
int rows;
printf("Number of complete lines >> " );
scanf("%d" , &rows);
return rows;
}
void writeTab(Tab* tab) {
int i;
i = 0;
for (i = 0; i < 5; i++)
fprintf(tab->fp, "%s\n" , tab->tabStr);
fprintf(tab->fp, "%s" , tab->tabStr);
}
int main(void ) {
Tab tab;
tab.songLen = allocateTab();
tab.songLen += 3;
tab.tabStr = malloc(sizeof (char ) * tab.songLen);
makeTab(&tab);
nameOfFile(&tab);
tab.fp = fopen(tab.fileName, "w" );
writeTab(&tab);
fclose(tab.fp);
return EXIT_SUCCESS;
}
Last edited on Jul 1, 2018 at 6:15am UTC
Jul 1, 2018 at 7:03am UTC
scanf("%s" , tab->fileName); // core dump here
tab->fileName is NULL
In your function makeTab you forgot to terminate tab->tabStr with a '\0'
Topic archived. No new replies allowed.