0

so I am trying to read a file with various university names with laptops and other information in c and then print them to the screen with a calculated cost/gb of ram, but am having trouble checking for EOF. I tried fscanf but this took away the first character of my first string, and am now trying fgets but this is taking away the first line of the file. I am wondering how I can avoid either of these while still checking for EOF. Thanks.

#include <stdio.h>

int main() {

  FILE *text; //Defining file pointer
  char end[100]; //EOF check

  //Headers
  char name[20] = "University"; 
  char lap[20] = "Laptop"; 
  char ram_[20] = "Ram";
  char gb_[20] = "Storage";
  char price_[20] = "Price";
  char costram_[20] = "Cost/Gb of ram";

  int ram;
  int gb;
  float price;
  float costram; //Cost/gb of ram

  printf("\n%10s %12s %8s %10s %12s %16s\n", name, lap, ram_, gb_, price_, costram_);


  text = fopen("text.txt", "r");

  //If file cannot be opened
  if (text == NULL){
    printf("Error opening file");
  }
  //File is opened
  else{
    //fscanf took away the first letter in my first string since it scanned it so I used fgets to compare with NULL instead 
    while (fgets(end, 100, text) != NULL){
        fscanf(text, "%s%s%d%d%f", name, lap, &ram, &gb, &price);
        costram = price / ram;
        printf("\n%10s %12s %6dgb %8dgb %12.2f %12.2f", name, lap, ram, gb, price, costram);
      }
    }
  return 0;
}

Replit link:https://repl.it/@Michael2022/Hardware-Assignment

Vishnu CS
  • 748
  • 1
  • 10
  • 24
  • 1
    Does this answer your question? [Detecting EOF in C](https://stackoverflow.com/questions/1428911/detecting-eof-in-c) – roottraveller Mar 26 '20 at 06:01
  • this is a very bad code practice i see here. please try to work on that too. – roottraveller Mar 26 '20 at 06:02
  • 5
    Why do you need to explicitly check for `EOF`? Why can't you just keep calling `fgets` until it returns `NULL`? Don't try to use `fgets/fscanf` **just** for the purpose of checking `EOF`. Instead, use `fgets` for the actual reading of a line and then use `sscanf` to parse the line read by `fgets`. – kaylum Mar 26 '20 at 06:03
  • 1
    Thou shall not *skmp on buffer size*... `char end[1024];` makes more sense (unless you are on a memory limited embedded system) -- in addition to the `fgets()/sscanf()` fix. – David C. Rankin Mar 26 '20 at 06:49
  • C and C++ are different languages. Please don't tag both unless you're asking about the differences between them. – molbdnilo Mar 26 '20 at 08:14
  • Can you please remove the C++ tag. – A M Mar 26 '20 at 08:51

0 Answers0