question about C linux read() write() - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

question about C linux read() write()

I'm very new to linux and C. I am just trying to figure out how some of this stuff works. I'm trying to write something that compares the amount of time it takes to copy a file depending on the buffer size and which function is used. When I run this, and I look at the output file, it is not the same as the input file. This is happening when I use fwrite and the regular write() function. Does anyone know why this is happening? Thanks in advance. Here is the code:

[code]

#include
#include
#include
#include
#include
#include

struct timeval cur;

void cur_time();
void after_time(const char* command);

int main(void)
{
int choice;
int buffsize;
size_t read_flag = 1;
char read_file[20];
char write_file[20];

printf("Enter File name to read with open command:
");
scanf("%s", read_file);
printf("Enter preffered buffer size:
");
scanf("%d", &buffsize);

unsigned char buffer[buffsize];

printf("Enter 1 for fopen functions or 2 for open functions");
scanf("%d", &choice);
printf("Enter file name to write to:
");
scanf("%s", write_file);

/*********** Using fopen *************/
if(choice == 1){

cur_time();

FILE * file = fopen(read_file, "r");
FILE * file2 = fopen(write_file, "w");

while(read_flag != 0){
read_flag = fread(buffer, buffsize, 1, file);
fwrite(buffer, buffsize, 1, file2);
}
fclose(file);
fclose(file2);

after_time("f commands");
}


/*********** Using open *************/
else{

cur_time();

int fd1 = open(read_file, O_RDONLY);
int fd2 = open(write_file, O_CREAT | O_WRONLY, S_IRWXU);

while(read_flag != 0){
read_flag = read(fd1, buffer, buffsize);
write(fd2, buffer, buffsize);
}
after_time("open");
}

}
void cur_time()
{
gettimeofday(&cur, NULL);
printf("%ld.%ld is the current time.
", cur.tv_sec, cur.tv_usec);
}

void after_time(const char* command)
{
gettimeofday(&cur, NULL);
printf("%ld.%ld is the time after %s is used
", cur.tv_sec, cur.tv_usec, command);
}
[/code]


Sign In or Register to comment.