Saturday, 15 February 2014

I am completely new to C programming and keep getting a segmentation fault -


This property is for the reservation system, which takes a .txt file that contains rows of int string string int Reads and put in a variety of rooms ... while this scanning gives me the fault of division ... it is for class and I do not want a code ready for a clerk, but I can not get why why I have a division Has been ...: /

#include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; Typedef Structure {int num; Four first [100]; Four past [100]; Int type; } Room; Int main (int argc, char ** argv) {FILE * myFile; If (argc! = 2) {fprintf (stderr, "Usage:% s & lt; filename»; \ n ", argv [0]); Return EXIT_FAILURE; } MyFile = fopen (argv [1], "r"); If (myFile == tap) {fprintf (stderr, "do not open !!"); Return EXIT_FAILURE; } // counter to add element to my array int i = 0; Four c; // It has an array of rooms with 150 rooms ... rooms * rooms = mallok (150 * size (rooms)); While ((c = getc (myFile))! = EOF) {fscanf (myFile, "% d", room [i] .num); Printf ("Room number is:% d", room [i] .num); Fscanf (MyFile, "% s", Room [i]. First); Fscanf (myFile, "% s", room [i] .last); Fscanf (myFile, "% d", room [i]. Type); I ++; } Fclose (myFile); }

Here's what's fixed and worked in my code, but it's really leaving the fist integer in the .txt file which reads it ... it only reads a zero when It should be 1 so I saw that "(c = getc (myFile))! = EOF" was my problem, it is to leave the first integer that should be read: /

  while (( C = getc (myFile))! = EOF {fscanf (myFile, "% d", and rooms [i] .num); Fscanf (MyFile, "% s", Room [i]. First); Fscanf (myFile, "% s", room [i] .last); Fscanf (myFile, "% d", and rooms [i]. Type); Printf ("The room number is:% d and it has been captured by% s% and it is% d \ n", the room [i] .num, room [i] first, room [i] room, Rooms [I mark); I ++; }  

The first line of the .txt file is as follows: 1 Carry Alston 0

In your code

  fscanf (myFile,"% d ", room [i] .num);  

should be

  fscanf (myFile, "% d", and the room [i] .num); With   object  

with that, you should always fscanf () appropriate scan < To ensure / code> ning,

Also, you need to enter a check on the value of i so that it should not be accessed to the bound memory.


No comments:

Post a Comment