c strcpy 文件描述符

发布于 2024-10-11 07:00:48 字数 697 浏览 5 评论 0原文

我对 strcpy() 函数有疑问。我想做的是用户输入一个文件名,然后我基本上打开该文件,获取内容并创建文件副本。

但是,我决定在写入之前进行一些错误检查,以检查 read() 的内容是否与复制文件中写入的内容相同。因此,我使用读取的文件大小将内容 read() 到动态数组中,因此缓冲区是数据的正确大小。然后我想将其创建一个副本到另一个动态缓冲区中,并使用 strcmp() 来查看它们是否相同,如果是,那么我将复制缓冲区写入输出文件?

这对于某些文件来说效果很好,但是视频文件(mpeg)等有问题,当打开视频文件时出现错误“无法确定流的类型”,这就是想法

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, buffer2, filesize); //write copied buffer to file
}
free(buffer1); free(buffer2);

好吧,我在内存中创建另一个缓冲区副本的原因是这样我可以比较实际的位数据,而不仅仅是大小,所以我知道正在写入的数据与正在读取的数据相同?

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, buffer2, 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傻比既视感 2024-10-18 07:00:48

strcpystrcmp 用于 C 字符串,以 0 结尾。如果您的视频文件有任何值为 0 的字节,它们将立即停止。

您应该改为查看 memcpymemcmp,它们不会将您的缓冲区解释为以 0 结尾的字符串。

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.

猫性小仙女 2024-10-18 07:00:48

您应该使用 memcpy 代替,因为 strcpy 只会复制到第一个 '\0' 字符。这对于二进制文件来说效果很差。真正的问题是为什么你想将文件的内容复制到内存中......你可以将原始缓冲区写到新文件中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文