Project

General

Profile

Bug #6503 ยป tseek.c

test program - Richard PALO, 2015-12-09 07:00 AM

 
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4

    
5
int
6
main(int argc, char **argv)
7
{
8
	FILE *fp;
9

    
10
	if (argc != 4) {
11
		printf("try again, syntax: %s <filename> string1 string2\n",
12
		    argv[0]);
13
		exit (1);
14
	}
15

    
16
	fp = fopen(argv[1], "a+b");
17
	if (fp != NULL) {
18
		char buffer[2048];
19
		int br, bw;
20

    
21
		/* start at the end of the file to allow appending */
22
		(void) fseek(fp, 0, SEEK_END);
23

    
24
		bw = fwrite(argv[2], 1, strlen(argv[2]), fp);
25
		printf("wrote %d bytes\n", bw);
26

    
27
		if (fseek(fp, 0, SEEK_SET))
28
			perror("1st fseek");
29

    
30
		br = fread(buffer, 1, sizeof(buffer), fp);
31
		if (br != 0) {
32
			printf("read: %d, offset: %d\n",
33
			    br, (int)ftell(fp));
34
		} else if ( ferror(fp) ) {
35
			perror("fread");
36
		} else if ( feof(fp) ) {
37
			printf("end of file, read: %d\n", br);
38
		}
39

    
40
		bw = fwrite( argv[3], 1, strlen(argv[3]), fp);
41
		printf("wrote %d bytes\n", bw);
42

    
43
#if	defined(H1)
44
		(void) fflush(fp);
45
#elif	defined(H2)
46
		if (fseek(fp, 0, SEEK_END))
47
			perror("H2 fseek");
48
#endif
49
		/* the following seek should automatically flush() */
50
		if (fseek(fp, 0, SEEK_SET))
51
			perror("2nd fseek");
52

    
53
		printf ("seeked to the beginning, offset: %d\n",
54
		    (int)ftell(fp));
55
		
56
		br = fread(buffer, 1, sizeof(buffer), fp);
57
		if (br != 0) {
58
			printf("read: %d, offset: %d\n",
59
			    br, (int)ftell(fp));
60
		} else if ( ferror(fp) ) {
61
			perror("fread");
62
		} else if ( feof(fp) ) {
63
			printf("end of file, read: %d\n", br);
64
		}
65

    
66
		(void) fclose(fp);
67
		exit(0);
68
	} else {
69
		perror(argv[1]);
70
		exit(1);
71
	}
72
}
    (1-1/1)