1

I'm trying to use low level functions in C and wanting to read from the STDIN and store that information in a file.

int dash, c;
char buffer[1024];
if((dash = creat("file.txt", S_IRWXU)) < 0)
    perror("creat error");
while ((c = read(STDIN_FILENO, buffer, sizeof(buffer))) > 0) {
    if (write(dash, buffer, c) != c)
       perror("write error");

I having a problem understanding how I can access 'file.txt' to read it to either print to the screen or store to another file. Would I just use 'read("file.txt", buffer, sizeof[buffer])'?

EDIT Now after creating "file.txt" I want to open another file, lets say file1 (argv[3]) and dump "file.txt" into file1 (agrv[3]). Would this work?

fd = open(argv[3], O_RDWR); //open 3rd arg for writing
fd_2 = open("file.txt", O_RDWR); //open created file
do {
     n = read(fd_2, buffer, sizeof(buffer));
     if (n < 0)
        perror("read error argv[2]"); //greater 0=succesful
     write(STDOUT_FILENO, buffer, n); // this is where I'm stuck
    } while (n == sizeof(buffer));
close(fd);

I have both files open now but can't figure out how to write "file.txt" into argv[3].

MBan
  • 58
  • 1
  • 5
  • If you use `creat()`, you zap the previous content of the file; it is empty. There's nothing to read. – Jonathan Leffler Oct 30 '13 at 05:17
  • But what if it's the first time "file.txt" is being written into, I should still be able to read from it to copy its contents to another file right? – MBan Oct 30 '13 at 05:23
  • If the file is created, it is empty. You can, of course, copy the zero bytes to another file if you so wish, but it is a modestly pointless exercise. After `creat()`, there is nothing in the file to read until you have written some data to the file. POSIX defines [`creat()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/creat.html) saying: _The `creat()` function shall behave as if it is implemented as follows: `int creat(const char *path, mode_t mode) { return open(path, O_WRONLY|O_CREAT|O_TRUNC, mode); }`_ so the file descriptor isn't readable when you've used `creat()`. – Jonathan Leffler Oct 30 '13 at 05:27
  • So if I used "S_IRWXU" as my mode in my creat() do I have to open() so I can write() into it? Thanks for your help btw. – MBan Oct 30 '13 at 05:35
  • With `creat()`, the file is open for writing (only; you can't read from that file descriptor), and the file is empty (until you do write something into it). Generally, the `creat()` system call is not used these days; it survives because it was necessary before [`open()`](http://plan9.bell-labs.com/7thEdMan/v7vol1.pdf) acquired the `O_CREAT` and related flags — many years ago now. – Jonathan Leffler Oct 30 '13 at 14:20
  • For the edited question, you are still writing to `STDOUT_FILENO`, you should write to `fd` instead. BTW, your editing is a different question. You should leave the question as it was, and ask a new one. – Yu Hao Oct 31 '13 at 06:05
  • You can't read from `fd` since it was opened with the following flags: `[O_WRONLY | O_CREAT | O_TRUNC]`, these flags are set by default by `creat`. Use `open` instead with `O_RDWR` (Read, Write). – Roi Mar 19 '21 at 19:05

2 Answers2

3

Use open() to get the file descriptor:

int fd = open("file.txt", O_RDWR);

Then you can use read() to read from this file descriptor just like STDIN_FILENO.

c = read(fd, buffer, sizeof(buffer));

Make sure to check for the return value of both functions in real code.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
0

Try the code. give the input filename as second argument.

#include<stdio.h>
#include<fcntl.h>

#define MAX_BUF_SIZE 512

int main(int argc, char **argv)
{
        int fd;
        int count,value;
        char buf[MAX_BUF_SIZE];

        if(argc < 2)
                fprintf(stderr, "Usage: a.out filename\n");
         else
        {
                 fd = open(argv[1], O_RDONLY);
                 if(fd < 0 )
                        fprintf(stderr, "Error In Opening File\n");
                else
                {
                        fprintf(stdout, "Enter No of bytes to read from file %s\n",argv[1]);
                        fscanf(stdin,"%d",&value);
                        printf("value %d\n",value);

                        count = read(fd,buf,value);
                        buf[count]='\0';

                        if(count <=0)
                                fprintf(stderr, "Error In Reading from file\n");
                        else if(count < value)
                                fprintf(stdout, "Partial read data is %s\n",buf);
                        else if(count == value)
                                fprintf(stdout, "Data is: \n%s\n",buf);
                        else
                                fprintf(stderr,"Error in read.");

                close(fd);
                }
        }
        return 0;
}

The '\0' is added to buffer to avoid any garbage value with the output.

Note: fopen,fread are library fn where open, read are system call

PearL
  • 16
  • 4
  • Is scanf a low-level function? – MBan Oct 30 '13 at 12:58
  • @MBan : I have updated my code. Thanks for reminding me. Difference between `open` & `fopen`,reffer: http://stackoverflow.com/questions/1658476/c-fopen-vs-open http://stackoverflow.com/questions/584142/what-is-the-difference-between-read-and-fread – PearL Oct 31 '13 at 06:43