0
votes

I get weird values after reading from file (i should be max 100 but I get more), and if someone would explain when to use & * ** in pointers in a simple why couse my english is not very good when it comes to programing I would be grateful

This program should read words from file and if there is a number in the word change it to first letter of that word. If you have any suggestions on how I could change file reading I would also appreciate that. I am new to C (in school I did C++ but very basic levels)

# include <stdio.h>
# define  MAX_LEN  100
int File_reading();
int main()
{char buffer;
  File_reading();
}

int File_reading(  )
{
   FILE *stream;
   char buffer[MAX_LEN + 1];
   int i, ch;

   stream = fopen("data.txt","r");

   for (i = 0; (i < (MAX_LEN+1));i++)
         {
        if (((ch = fgetc(stream)) != EOF) && (ch != '\n'))
            {
            buffer[i] = ch;
            }
         }
   buffer[i] = '\0';

   if (fclose(stream))
      perror("fclose error");
for (i=0;(i<(MAX_LEN+1));i++){

   printf("%c \n", buffer[i]);
   }
}
1

1 Answers

2
votes

You're not stopping the loop when the file is over, and you're overstepping the array bound! That's terrible. Fix the loop, like this:

char buffer[MAX_LEN + 1];
size_t i;

for (i = 0; i != MAX_LEN; ++i)
{
    int c = fgetc(stream);
    if (c == EOF) { break; }
    buffer[i] = c;
}

buffer[i] = '\0';