EmbLogic's Blog

FILE read and write

I am performing file read and write operations

everything is working fine but my function is not

checking EOF. It is not coming out of loop even if

i had applied a condition (if character is equal to EOF

).

 

/*main file

File name : file_main.c*/

 

#include”myheader.h”

int main(int argc,char *arg[])
{
int fptr,ch;
fptr = open(arg[1],O_RDONLY);
if(fptr == -1)
{
perror(“file does not exist \n”);
exit(EXIT_FAILURE);
}
while(1)
{
printf(“press 1: to read 2: to copy to another file 3: to compress4: exit”);
scanf(“%d”, &ch);
switch(ch)
{
case 1: read_file(fptr);
break;
case 2: copy_file(fptr);
break;
case 3: compress_file(fptr);
break;
case 4: exit(0);
}
}
}

 

/*file functions.c — function definitions are

present in this file*/

/* file name : file_functions.c*/

#include”myheader.h”

void read_file(int fptr)
{
char ch = ”;
int i;
read(fptr,&ch,1);
while(1)
{
if(i != 0)
{
write(1,&ch,1);
}
i = read(fptr,&ch,1);
if(ch == EOF)
{
printf(“******* FILE COMPLETE ********\n”);
break;
}
}
}

void copy_file(int fptr)
{
int file_d,i;
char ch = ”;
file_d = open(“copy.txt”,O_CREAT | O_WRONLY);
if(file_d == -1)
{
perror(“ERROR IN COPY FUNCTION : \n”);
exit(EXIT_FAILURE);
}
while(1)
{
i = read(fptr,&ch,1);
if(i == 0)
{
continue;
}
if(ch == EOF)
{
break;
}
i = write(file_d,&ch,1);
while(i == 0)
{
i = write(file_d, &ch,1);
}
}
}

void compress_file(int fptr)
{
}

 

/*make file */

FILE:file_functions.o file_main.o
gcc -o FILE file_main.o file_functions.o
file_main.o:file_main.c myheader.h
gcc -g -c file_main.c
file_functions.o:file_functions.c myheader.h
gcc -g -c file_functions.c

clean:
rm *.o
rm FILE copy.txt

One Response to FILE read and write

  1. Manoj says:

    Please use \n with all the printf() statements…
    This may cause IO problem…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>