c strcpy a file descriptor
I have a question with strcpy() function. What I am trying to do is the user enters a file name and I basicly open the file, gets contents and create copy of file.
However, I decided to do some error checking to check if the content read() is the same as content written in copy file before writing it. So, I read() content into dynamic array using the file size of file read, so buffer is the right size for data. I then want to create a copy of that into another dynamic buffer, and use the strcmp() to see if they the same, if so then I write the copy buffer to the output file?
This works fine for certain files but problem with video files(mpeg) etc, when opening a video file get error 'Could not determine type of stream', heres the idea
char* buffer1 = malloc(filessize);
char* buffer2 = malloc(filessize);
read(file, buffer1, filesize);
strcpy(buffer2, buffer1); //copy buffer1 into buffer2
if(strcmp(buffer1, buffer2) == 0)
{
write(outputfile, buf开发者_运维技巧fer2, filesize); //write copied buffer to file
}
free(buffer1); free(buffer2);
Well the reason why I created another copy of buffer in memory is so I can compare the actual bit data, not just size, so I know that the data being written is the same as data being read?
strcpy
and strcmp
are for C strings, which are 0 terminated. If your video files have any byte with a value of 0, they will stop right there.
You should look at memcpy
and memcmp
instead, which won't interpret your buffers as 0 terminated strings.
You should use memcpy instead, as strcpy will only copy until the first '\0'-character. This works badly for binary files. The real question is why you want to copy the contents of the file in memory though... You could just write out the original buffer to a new file.
精彩评论