Path: utzoo!attcan!uunet!munnari.oz.au!uniwa!bilby.cs.uwa.oz.au!kowari!kim From: kim@bilby.cs.uwa.oz.au (Kim Shearer) Newsgroups: comp.lang.c Subject: ftell fseek Summary: Problem updating files Keywords: ftell fseek r+ Message-ID: Date: 12 Dec 90 08:33:33 GMT Organization: Dept. Computer Science, University of Western Australia. Lines: 61 I have been trying to come to terms with file processing in C. After reading the manuals etc... I have still not solved my problem What I am trying to do is read %s %d pairs from a file, and update the %d part if the %s matches a certain value. To do this I use ftell to keep track of where I wish to put the number. I realise that if things arn't the same size.... but the big problem is this : the ftell returns 3 (see example file below) and is stored in a long, yet the fseek imediately following resets the file to the start. I even read the fine print sating that in an update opened file you must seperate in and out operations by resets or fseeks. If anyone can tell me what is wrong or that this is incorrect use of the "r+" opened file and why, I would be very grateful. EXAMPLE FILE ----------------- bob 2 fred 2 ----------------- CODE ----------------- #include #define MAX_NAMELEN 64 int my_index, my_ndepts = 0; FILE *my_file_p; main () { int dept_no, hours_wrkd, i, old_hours, i_own_it = 0; char update_name[MAX_NAMELEN], name[MAX_NAMELEN]; char filename[MAX_NAMELEN]; int err_ret; long marker; sprintf (filename, "department%d", 2); my_file_p = fopen (filename, "r+"); if (my_file_p == NULL) { printf (" %d could not open file %s\n", my_index, filename); perror (filename); exit (0); } fseek (my_file_p, 0L, 0); while (fscanf (my_file_p, "%s", name) == 1) { marker = ftell (my_file_p); fscanf (my_file_p, "%d", &old_hours); if (strcmp ("bob", name) == 0) { err_ret = fseek (my_file_p, marker, 0); printf (" fseek returns : %d\n", err_ret); fprintf (my_file_p[i], " %d", old_hours + hours_wrkd); err_ret = fseek (my_file_p, marker, 0); fscanf (my_file_p[i], "%d", &old_hours); } } }