Hello to you all ,

I am having a little trouble in C , working with Files.
for some reason , it doesnt copy to output file the first letter and jumps
over 3 digits of the last number in the file .

whats wrong , i cant find it .

yotam

P.S - source and Input.txt included

Dani AI

Generated

A quick diagnosis and practical fixes.

The symptoms you describe (first character missing; the last number losing digits) almost always come from undefined behaviour — typically memory corruption or reading/parsing errors. was right to look at initialization and how lines are parsed. Start by treating every pointer, counter and buffer as something that must be set to a known value before use, and isolate parsing from storage so you can see exactly where data is lost.

Parse each input line safely (tokenize and convert rather than blind %s), limit string copies, and validate every conversion. Example tokenizing approach:

char line[256], name[64];
while (fgets(line, sizeof line, in)) {
  char *tok = strtok(line, " \t\r\n");
  if (!tok) continue;
  strncpy(name, tok, sizeof name-1);
  name[sizeof name-1] = '\0';
  tok = strtok(NULL, " \t\r\n");                 /* id */
  long id = tok ? strtol(tok, NULL, 10) : 0;
  tok = strtok(NULL, " \t\r\n");                 /* avg */
  float avg = tok ? strtof(tok, NULL) : 0.0f;
  tok = strtok(NULL, " \t\r\n");                 /* hw */
  long hw = tok ? strtol(tok, NULL, 10) : 0;
  /* push these safely into your array after checking allocations */
}

To avoid the “double menu” effect, read user choices with a line read and take the first character:

char buf[16];
if (fgets(buf, sizeof buf, stdin)) {
  char choice = buf[0];
  /* use choice */
}

When copying/writing files, use size-aware I/O so nothing is lost:

unsigned char buf2[4096];
size_t n;
while ((n = fread(buf2, 1, sizeof buf2, in)) > 0)
  if (fwrite(buf2, 1, n, out) != n) /* handle error */;

Debugging tips: compile with all warnings enabled, run with AddressSanitizer or Valgrind if available, and add temporary diagnostics that print parsed fields before storing them. That will quickly show whether the loss happens during parsing or during storage.

Recommended Answers

All 3 Replies

> void main
main returns int

> char user_choice;
> while (user_choice!='z')
This variable is uninitialised at the point you first use it.

> university univ;
This isn't initialised either.
Which is very important when you get to make_file(), since you do
- dereference an uninitialised pointer
- try and realloc an uninitialised pointer

> if (un->ptr==NULL) un->ptr=(student*)realloc(un->ptr,(count+1)*sizeof(student));
The test serves no purpose, since at best it only extends the array once.

In main(), you need this to start off with a NULL pointer university univ = { 0 }; And this function needs to be something like

int make_file(FILE *in,university *un) {
  char buff[BUFSIZ];
  int  count=0;

  while ( fgets( buff, sizeof buff, in ) != NULL ) {
    student s;
    if ( sscanf( buff, "%s %ld %f %ld",
                 s.name, &s.id, &s.avg, &s.hw_submit ) == 4 ) {
      /* success decode, extend array and copy the info */
      void *temp = realloc( un->ptr, (count+1)*sizeof(student) );
      if ( temp != NULL ) {
        un->ptr = temp;          /* update array */
        un->ptr[count] = s;      /* copy data */
        count++;                 /* one more stored */
      } else {
        /* no more room, return with what we have */
        return count;
      }
    } else {
      /* that line didn't make sense, report it */
      fprintf( stderr, "Bad line %s", buff );
    }
  }
  return count;
}

> void main
main returns int

> char user_choice;
> while (user_choice!='z')
This variable is uninitialised at the point you first use it.

> university univ;
This isn't initialised either.
Which is very important when you get to make_file(), since you do
- dereference an uninitialised pointer
- try and realloc an uninitialised pointer

> if (un->ptr==NULL) un->ptr=(student*)realloc(un->ptr,(count+1)*sizeof(student));
The test serves no purpose, since at best it only extends the array once.

In main(), you need this to start off with a NULL pointer university univ = { 0 }; And this function needs to be something like

int make_file(FILE *in,university *un) {
  char buff[BUFSIZ];
  int  count=0;

  while ( fgets( buff, sizeof buff, in ) != NULL ) {
    student s;
    if ( sscanf( buff, "%s %ld %f %ld",
                 s.name, &s.id, &s.avg, &s.hw_submit ) == 4 ) {
      /* success decode, extend array and copy the info */
      void *temp = realloc( un->ptr, (count+1)*sizeof(student) );
      if ( temp != NULL ) {
        un->ptr = temp;          /* update array */
        un->ptr[count] = s;      /* copy data */
        count++;                 /* one more stored */
      } else {
        /* no more room, return with what we have */
        return count;
      }
    } else {
      /* that line didn't make sense, report it */
      fprintf( stderr, "Bad line %s", buff );
    }
  }
  return count;
}

I did so , however , only the first name was fixed .... how bizzare.
1. what does "buff" stands for , after all it has no Value.
2.BUFSIZ shoulde be defined or resized each reading from source file?
3.how can get rid of the double menu display?
4.is there a way to write to target file so it wont skip chars?

thanx salem

1. what does "buff" stands for , after all it has no Value.
buff is short for buffer.

2.BUFSIZ shoulde be defined or resized each reading from source file?
No, it is a fixed constant declared in stdio.h (for an ANSI-C compiler anyway).
You are using an ANSI-C compiler and not some ancient fossil like TurboC.

3.how can get rid of the double menu display?
Don't use getchar(), scanf(), getc() to read a single character.
Use fgets() to read a line from stdin, then read what you need from the buffer.
It's just like my use of fgets() in the previous post.

4.is there a way to write to target file so it wont skip chars?
I've no idea - post the problem code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.