Hi All,
I'm new to C-programming, and I'm trying to read a text file.
Here's my code so far.
Code:
#include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <errno.h> // external int errno
9
10 #define ACC_RIGHT 0644 /* User: Read+Write, Group and Other: Read */
11
12 int main(int argc, char *argv[])
13 {
14 /*int cmd_count;
15
16 printf("input= %s\n", argv[1]); // program name
17 printf("output= %s\n", argv[2]);
18
19 int fd; // file descriptor
20
21 if ((fd = open(argv[1], O_WRONLY, ACC_RIGHT)) < 0) {
22 //perror("Fault by open file "); exit(1);
23 printf("Cannot open file!\n");
24 } else {
25 printf("File has been openend!\n");
26 */
27
28 //#define BUFSIZE 128
29
30 //char buffer;
31
32 char c;
33 //char *pc;
34 char pc[512];
35 int nread;
36
37 //pc = &c;
38
39 //char buffer[512];
40
41 int filedes;
42 //ssize_t nread;
43 //long total = 0;
44 //int count = 0;
45
46 /* open the test file */
47 if ((filedes = open("test.txt", O_RDONLY)) == -1)
48 {
49 printf("Couldn't open test.txt \n");
50 } else {
51 printf("file is open!\n");
52 }
53
54 /* read in loop until EOF */
55 while (nread = read(filedes, pc, 1) > 0)
56 {
57 //printf("Read %d bytes this time \n", nread);
58 //count++;
59 //*pc ^= 31;
60
61 printf("char=%s\n", pc);
62
63 //total += nread;
64 }
65
66 //printf("char1=%s\n",pc);
67
68 //printf("char1=%s\n",c[0]);
69
70 //printf("Read %d bytes in total \n", total);
71 //}
72
73 return 0;
74 }
Here's my problem.
I do not want a fixed buffer size when reading text files, and I need to use the 'read' function.
I'm not new to programming, but C is new for me.
If I use a pointer, which is commented out in my code above (*pc / pc = &c; ), I'm getting strange characters at the end of the characters from my text file, e.g.:
char=R«ß..¿
instead of
char=R, which I get when using the above code, without commenting out the pointer code.
Please, Help! This is frustrating me.
Best Regards,
Kevin