/*********************************
name fileread1.c
description creat a temp file in size, and read() the file,
count speed read a character's speed
author akang
time 06-07-20
***********************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdio.h>
#include <string.h>
int creat_temp_file(char *dir, long int size)
{
char * filename = "/dir-XXXXXX";
char temp_filename[100];
memcpy(temp_filename, dir, strlen(dir)+1);
strcat(temp_filename, filename);
int fd;
if((fd = mkstemp(temp_filename)) == 0)
{
printf("creat temp file failed!\n");
return -1;
}
printf("%s\n", temp_filename);
unlink(temp_filename);
while(size > 0)
{
if(write(fd, "hello linux!", 12) == -1)
{
printf("write file failed!\n");
return -1;
}
size -= 12;
}
return fd;
}
void read_temp_file(int temp_file, long int size)
{
char *buffer;
int fd;
fd = temp_file;
lseek(fd, 0, SEEK_SET);
buffer = (char *)malloc(size);
read(fd, buffer, size);
close(fd);
free(buffer);
}
void input_argument(char *dir, long int size)
{
char *_buffer = NULL;
long int temp_size;
int fd;
temp_size = size;
#define PRINT_TIME 1
#ifdef PRINT_TIME
struct timeval tb, te;
double second ;
#endif
#ifdef PRINT_TIME
gettimeofday (&tb, NULL);
#endif
if((fd = creat_temp_file(dir, size)) != -1)
{
while(size > 0)
{
read_temp_file(fd, 512);
size -= 512;
}
#ifdef PRINT_TIME
gettimeofday (&te, NULL);
second = ((te.tv_sec - tb.tv_sec) * 1000000.0
+ te.tv_usec - tb.tv_usec) / 1000000.0;
printf("difftime : %f\n", second );
#endif
double t_size;
if(second == 0)
printf("don't read file!\n");
else
{
t_size = temp_size / second;
printf("read the file speed is %f b/s in %ld bytes\n",
t_size, temp_size);
}
}
else
{
printf("creat_temp_file failed!\n");
}
}
char * getmborkb( char * str, const char * agtname)
{
char *string;
int length;
length = strlen(str);
memcpy(string, str, length);
if(string[length-1] == agtname)
return (memcpy(str, string, (length-1)));
else if(isdigit(string[length-1]))
return str;
}
long int manageagt( char *str)
{
char *string, *temp_str;
long int rt = 0;
memcpy(string, str, strlen(str));
if(memcmp(string, (temp_str = getmborkb(string, "m")), strlen(temp_str)) != 0)
return (rt = strtod(temp_str, NULL) * 1024 * 1024);
else if(memcmp(string, (temp_str = getmborkb(string, "k")), strlen(temp_str)) != 0)
return (rt = strtod(temp_str, NULL) * 1024);
return (rt = strtod(temp_str, NULL));
}
int main(int argc, char *argv[])
{
char *dir,*temp_size;
long int size;
if(argc != 3)
printf("argument failed!\n");
dir = argv[1];
temp_size = argv[2];
/* size = manageagt(temp_size);
*/
size = strtod(temp_size, NULL);
input_argument(dir, size);
return 0;
}
哎,可惜了格式全變了