我实现了以下功能
int copy_files(char *source, char *destination)
{
FILE *in_fd, *out_fd;
char *buf;
char buffer[512];
time_t t;
struct tm *td;
long file_size;
int result;
int value;
int status = STATUS_ERROR;
/* Open file for both reading and writing */
in_fd = fopen(source, "w+"); //
if(in_fd == NULL)
{
fputs ("File error",stderr);
exit (1);
}
else
{
printf("writing in file...\n");
strcpy(buffer, "Test writing in USB Key File \n");
fprintf(in_fd, buffer);
printf("%s\n",buffer);
t = time(NULL);
td = gmtime((const time_t *)&t);
sprintf(buffer, "Date %02d/%02d/%02d Time %02d:%02d:%02d\n",
td->tm_mday, td->tm_mon + 1, td->tm_year + 1900,
td->tm_hour, td->tm_min, td->tm_sec);
fprintf(in_fd, buffer);
printf("%s\n",buffer);
printf("Writing OK\n");
}
out_fd = fopen(destination,"w+");
if(out_fd == NULL)
{
fputs ("File error",stderr);
exit (1);
}
else
{
// obtain file size:
fseek (in_fd , 0 , SEEK_END);
file_size = ftell (in_fd);
rewind (in_fd);
// allocate memory to contain the whole file:
buf = (char*) malloc (sizeof(char)*file_size);
while (!feof(in_fd))
{
/* Read data */
fread(buf, 1, (sizeof buf), in_fd);
printf("%s", buf);
}
/* Write data */
fwrite(buf, 1, (sizeof buf), out_fd);
}
fclose(in_fd);
fclose(out_fd);
return STATUS_OK;
}
通过此功能,我想创建一个文件,用两行填充它,然后将整个包含内容复制到另一个文件中。
但是我不明白为什么:
printf diplay:
在文件中写...在USB密钥文件中写测试日期1970年1月1日时间00:45:46在h vUSBh vKeyh vFileh中写OKTesth vwrih vtingh v vDah vte0h v1/01h v/197h v0Tih vme0h v0:45h v:46h v:46
如何解决问题?
编辑 :
关于第一个问题,我不明白为什么下面的代码:
strcat(temp_dest, direntp->d_name);
printf("after strcat temp_dest=%s\n", temp_dest);
strcat(temp_src, direntp->d_name);
printf("after strcat temp_src=%s\n", temp_src);
printf("destination:%s\n",temp_dest);
copy_files(temp_src,temp_dest);
返回:
after strcat temp_dest=/tmp/usb/test10
after strcat temp_src=/media/sda1/test10
destination:10
为什么是10?:/
更正您的fread()
。
既然你已经知道了filesize
。
无需循环,一个fread
读取file_size
字节的调用就足够了。
else
{
// obtain file size:
fseek (in_fd , 0 , SEEK_END);
file_size = ftell (in_fd);
rewind (in_fd);
// allocate memory to contain the whole file:
buf = malloc (file_size);
/* Read file_size no of bytes */
fread(buf, 1, file_size, in_fd);
buf[file_size -1] = 0;
printf("File content after Reading :[%s]", buf);
/* Write data */
fwrite(buf, 1, file_size, out_fd);
}
代码中的其他更正。
您在中缺少%s
(第二个参数)fprintf
。
...
else
{
printf("writing in file...\n");
strcpy(buffer, "Test writing in USB Key File \n");
fprintf(in_fd, "%s", buffer);
...
fprintf(in_fd, "%s", buffer);
printf("Writing OK\n");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句