I have a text file called "graphics" which contains the words "deoxyribonucleic acid".
When I run this code it works and it returns the first character. "d"
int main(){ FILE *fileptr; fileptr = fopen("graphics.txt", "r"); char name; if(fileptr != NULL){ printf("hey \n"); } else{ printf("Error"); } fscanf( fileptr, "%c", &name); printf("%c\n", name); fclose( fileptr ); return 0; } When I am using the fscanf function the parameters I am sending are the name of the FILE object, the type of data the function will read, and the name of the object it is going to store said data, correct? Also, why is it that I have to put an & in front of name in fscanf but not in printf?
Now, I want to have the program read the file and grab the first word and store it in name. I understand that this will have to be a string (An array of characters). So what I did was this: I made name into an array of characters that can store 20 elements.
char name[20]; And changed the parameters in fscanf and printf to this, respectively:
fscanf( fileptr, "%s", name); printf("%s\n", name); Doing so produces no errors from the compiler but the program crashes and I don't understand why. I am letting fscanf know that I want it to read a string and I am also letting printf know that it will output a string. Where did I go wrong? How would I accomplish said task?
fscanf, you'd better set a width.%19sfor example.