Reputation: 79
I'm currently working on a program that reads strings from a file and stores them into a 2-D array. However, when I try to print out the contents of the array, I get a random character every time. Here is my code:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE* file_pointer;
char user_input[80];
char line[81];
char all_lines_array[100][81];
int total_lines = 0;
while (1){
printf("Please enter a command: ");
scanf("%s", &user_input);
if (strstr(user_input, "read") != NULL){
file_pointer = fopen("C:\\Users\\Tyler\\Desktop\\Hello.txt","r");
while (fgets(line, 100, file_pointer)) {
line[strlen(line)+1] = "\0";
*all_lines_array[total_lines] = line; //My guess is this is wrong
total_lines++;
}
fclose(file_pointer);
}
}
return 0;
}
I suspect that this is because I'm incorrectly inserting string into my 2-D array, but I have no idea what it is I'm doing wrong. I've set the numbers so that there can only be a maximum of 100 lines in a file, and each line can only be 80 characters long (with the "\0"
at the end).
Here is my input file:
John Doe 1221 Washington St. 1234567
Jane Doe 1233 Washington St. 1234568
Cain Doe 1234 Washington St. 1234569
Upvotes: 0
Views: 246
Reputation: 33601
There where some statements flagged when compiling with -Wall
[which I always recommend doing], which may have helped with some of the errors.
Here's the corrected version, annotated with comments [please pardon the gratuitous style cleanup]:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main()
{
FILE *file_pointer;
char user_input[80];
char line[81];
char all_lines_array[100][81];
int total_lines = 0;
while (1) {
printf("Please enter a command: ");
// compiler flagged this with a warning
#if 0
scanf("%s", &user_input);
#else
scanf("%s", user_input);
#endif
if (strstr(user_input, "read") != NULL) {
#ifndef CRAIG
file_pointer = fopen("C:\\Users\\Tyler\\Desktop\\Hello.txt", "r");
#else
file_pointer = fopen("input.txt", "r");
#endif
if (file_pointer == NULL) {
printf("file not found\n");
continue;
}
// NOTE: using sizeof here is better as 100 was specified but
// "line" was only 81
while (fgets(line, sizeof(line), file_pointer)) {
// NOTE: I presume this is to strip the newline
// in the original form, it would add garbage chars to the end
// [because of "\0" instead of '\0']
#if 0
line[strlen(line) + 1] = "\0";
#else
line[strlen(line) - 1] = 0;
#endif
// NOTE: the compiler flagged this as well
#if 0
*all_lines_array[total_lines] = line; // My guess is this is wrong
#else
strcpy(all_lines_array[total_lines],line);
#endif
total_lines++;
}
fclose(file_pointer);
}
}
return 0;
}
Upvotes: 1
Reputation:
fgets is reading 100 chars but your static allocated variable char line[81]
is only allocates memory for 81 chars.
instead of the =
operator use strcpy
Upvotes: 0