I am cant seem to get my simple script to read the file. All i am trying to do is read letters into an array. I just get random characters and it is driving me crazy. I have the file in the Debug folder, what else can go wrong? I am 100 percent sure everything is correct.
Here is my code:
FILE * ifp;
ifp = fopen("letters.txt", "r");
int i;
int bound = 20;
char data[20];
for(i =0; i<bound; i++){
fscanf(ifp, "%s", &data[1]);
if (ifp == NULL){
return;
}
printf("Data %d = %c\n", i, data[i]);
}
Here's an example:
Sample output:
Note:
We're reading a line at a time
We're reading each line into an array
We define the #/elements in the array (MAX_LINES) and the maximum size of each string (MAX_LINE) ahead of time
We check for "file open error" (and return "non-zero" accordingly)
We use "fgets()" to safely read a line (without risking a buffer overrun).
If you wanted to read a character at a time, the program could be as simple as:
One problem with the second example is that it doesn't check for string length >> MAX_LINE. But hopefully it helps give you some ideas...
Hmm could it be because
should be just
or the equivalent
which is likely what you intended.
?
Only other reason I can think of is, the line you are reading is greater than 20 characters and its overflowing the data array.
Have a look at this example: http://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm
The following code