Makefile support for sparc-ros-gcc
[akaros.git] / user / apps / parlib / file_io.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <stdio.h>
7 #include <unistd.h>
8
9 #define IN_BUF_SIZE 1024
10
11 extern char * readline(const char *prompt);
12
13 void file_io()
14 {       
15         printf("Beginning Ethernet Based File IO Test...\n\n");
16         int in_fd = open("sample", O_RDWR, 0);
17         printf("Opened:       sample\n");
18         printf("FD:           %d\n", in_fd);
19         char buf[IN_BUF_SIZE];
20         int read_amt = read(in_fd, buf, IN_BUF_SIZE - 1);
21         buf[read_amt] = '\0';
22         printf("Read:         %d bytes\n", read_amt);
23         printf("Data read:    %s", buf);
24
25
26         char * readline_result = readline("\nEnter filename for writing: ");
27         if (readline_result == NULL) {
28                 printf("Error reading from console.\n");
29                 return;
30         }
31
32     unsigned int fname_len = strlen(readline_result) + 1;
33         char * file_name = malloc(fname_len);
34         strncpy(file_name, readline_result, fname_len);
35
36         readline_result = readline("Enter text to write to file: ");
37
38         if (readline_result == NULL) {
39                 printf("Error reading from console.\n");
40                 return;
41         }
42
43
44         unsigned int buf2_len = strlen(readline_result) + 1;
45         char *buf2 = malloc(buf2_len);
46         strncpy(buf2, readline_result, buf2_len);
47
48
49         unsigned int ofp_len = strlen(file_name) + 8;
50         char * output_full_path = malloc(ofp_len);
51         snprintf(output_full_path, ofp_len, "%s", file_name);
52
53         int out_fd = open(output_full_path, O_RDWR | O_CREAT | O_TRUNC,
54                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
55
56         printf("\nOpened:       %s\n", file_name);
57         printf("FD:           %d\n", out_fd);
58
59
60         int write_amt = write(out_fd, buf2, strlen(buf2));
61         
62         printf("Wrote:        %d bytes\n", write_amt);
63
64
65         int in_fd2 = open(output_full_path, O_RDWR, 0);
66         read_amt = read(in_fd2, buf, IN_BUF_SIZE - 1);
67         buf[read_amt] = '\0';
68         printf("Data written: %s\n\n", buf);
69
70         printf("Closing remote file descriptor: %d.... %s\n", in_fd, ((close(in_fd) == 0) ? "successful" : "failure"));
71         printf("Closing remote file descriptor: %d.... %s\n", out_fd, ((close(out_fd) == 0) ? "successful" : "failure"));
72         close(in_fd2);
73
74         printf("\nTests Complete.\n\n");
75 }