Click here to Skip to main content
14,580,625 members
Rate this:
Please Sign up or sign in to vote.
See more:
How can I read the data from a file containing integer values and write them to two different .txt files based on the condition whether the value is even or odd by using only system call functions read()/write()?

What I have tried:

#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
void main(int argc,char *argv[])
{
int fd1,fd2,fd3,n,i,buf[100];
fd1=open(argv[1],O_RDONLY);
fd2=open(argv[2],O_WRONLY);
fd3=open(argv[3],O_WRONLY);
n=read(fd1,buf,sizeof(buf));
for(i=0;i<n;i++)
{
if(buf[i]%2==0)
{
write(fd2,buf,n);
}
else
{
write(fd3,buf,n);

}
}
close(fd1);
close(fd2);
close(fd3);
}
Posted
Updated 15-Dec-19 7:57am
v2

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

First, look at your data file, and decide how it is organised: if it contains "integers" then you need to find out how it's actually stored.
For example:
1234
5678
9012
is probably string representation of integers, not "integers" per se. To read those, you need to read lines to establish where integers start and finish, and identify the final character of each value in order to decide if the integer number is even or odd.
Even if it's stored differently, you will need to do something similar, as it';s very unlikely that each integer is stored in a directly useful format.

And do yourself a favour: indent your code!
It's a lot easier to work out what is happening if you indent it:
for(i=0;i<n;i++)
    {
    if(buf[i]%2==0)
        {
        write(fd2,buf,n);
        }
    else
        {
        write(fd3,buf,n);
        
        }
    }
Is much easier to work with than
for(i=0;i<n;i++)
{
if(buf[i]%2==0)
{
write(fd2,buf,n);
}
else
{
write(fd3,buf,n);

}
}
   
Comments
CPallini 15-Dec-19 16:05pm
   
5.
k5054 15-Dec-19 21:19pm
   
To the OP, also note that open("my_file.txt", O_RDONLY) does not create "my_file.txt", if it does not already exist. For that you will need to use the O_CREAT flag. There being several reasons that open might fail, you should probably check its return value e.g.
int fd;
fd = open("my_file.txt", O_RDONLY)
if(fd == -1) /* open failed */
{ 
    // handle the error here ...
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100