Click here to Skip to main content
15,878,959 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

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:
C++
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
C++
for(i=0;i<n;i++)
{
if(buf[i]%2==0)
{
write(fd2,buf,n);
}
else
{
write(fd3,buf,n);

}
}
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900