I'm having an issue within the first while loop, it prints out 1 then crashes. Eclipse doesn't give me any errors. It pops up a windows alert box saying Assignment2 has stopped working. I think it has something to do with memory location access or something. Any idea why this won't work properly? It's suppose to read in a text file and store it word by word.
It's probably crashing at line 36 where it tries to write a string to a NULL pointer.
There is no memory allocated to data. Is this what lines 42, 43 are for?
If you put that after line 6 then you would know how many characters to allocate to data so the string can be stored there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
printf("Type in the name of the file containing the Field\n");
scanf("%s", &file_name);
printf("Type in the number of characters per line:\n");
scanf("%d", &num);
fptr = fopen(file_name, "rt");
//having an issue with this while loop
while (read != 0) {
printf("%d", read);
current->nextPtr = malloc(sizeof(LISTNODE));
current = current->nextPtr;
// current->data = NULL;
current->data = (char*)malloc(num*sizeof(char));//allocate storage for the string
read = fscanf(fptr, "%s", current->data);
printf("\n");
current->nextPtr = NULL;// mark as end of list, in case this is the last node.
}
Sorry i didn't explain the overall goal of the code. The user will be asked to enter in the number of characters per line so i can print the file with type justification depending on the number of characters they want per line.
It reads a file of text so how am i suppose to determine the size of current->data?
Can you anticipate a maximum length for the strings being read from the file?
I don't program in c so I don't know the methods well;
I would declare a char array that's really big. char temp[1000];
then read each string into that read = fscanf(fptr, "%s", temp);
then find the actual string length int length = strlen(temp) + 1;// allow room for the terminating '\0'
then allocate that much to data current->data = (char*)malloc(length*sizeof(char));
finally, copy from temp to data strcpy(current->data, temp);
i tweaked my code a little bit and it prints semi-justified. The only issue i have now is trying to add spaces in between each word to even it out. So if i specify there can only be 20 characters printed on each line, and all the words only add up to say, 16 characters, i need to distribute 4 spaces inbetween the words. How do i go about doing this? I should have some sort of loop inside my loop that prints the current->data?