0

I am working on assignment for encryption. I am currently trying to read a file and print its ASCII values in the console before writing the values into a file. I am having a problem with my printing, the program is printing the correct ASCII values, however, the program is printing '-1' after it is done reading the file values.

The file has the following written within it:

  1. Test file, ASCII Read

This is the output of the program: 49 46 32 84 101 115 116 32 102 105 108 101 44 32 65 83 67 73 73 32 82 101 97 100 -1

As you can see, the -1 does not correspond to any of the values within the txt file

Thank you in advance

I tried to switch the lines within the while loop but that prints a 0 at the start, I need the values to be printed so that I can use them for encryption.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    

    //file read/file open

    FILE *ptr;                                        //create file pointer

    char fileName[100];                               //variable to hold file name
    char fileVal;                                     //variable to store file character values

    //ask user for file name
    printf("Please enter the file name\n");
    scanf("%s", fileName);                      //store user input as file name

    ptr = fopen(fileName,"r");           //open file with pointer

    //create while loop to read file and print character by character
    while(!feof(ptr)){
        fileVal = fgetc(ptr);                           //store each character read from the file within the variable
        printf("%d ", fileVal);                      //print all file characters
    }

    fclose(ptr);                                  //close file



    return 0;
}

Progman
  • 16,827
  • 6
  • 33
  • 48
  • See https://stackoverflow.com/questions/18839503/feof-on-linux-return-true-at-one-line-later-than-the-ending-line https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong – dave_thompson_085 Nov 14 '22 at 19:39
  • @dave_thompson_085 Thank you that helped me figure it out! – rEeYaN__ Nov 14 '22 at 20:10
  • `char fileVal;` should be `int fileVal;` It's the mandatory beginner's mistake. Most library functions to not use `char` and here the function is `int getchar();` so you can distinguish `EOF` from `0xFF`. – Weather Vane Nov 14 '22 at 20:11

0 Answers0