我正在尝试编写代码(用 C 语言),该代码将从一个文件中读取,并写入创建的文件。我唯一苦苦挣扎的部分是 while 循环,它应该连续读写直到文件结束。我得到前 120 个字符,写入它们,然后将 'XYZ' 写入文件,但是当我再次尝试读/写时,我得到 ^@ 和一堆垃圾。我不想要如何做到这一点的解决方案,只需告诉我我做错了什么/忘了做什么。
#include <sys/types.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
void main()
{
int a, b, c;
int XYZ = creat("XYZ.doc", 777);
if(XYZ<0) {
printf("error with creat");
exit(0);
}
int xxxx = open("/usr/class/cis660/xx.xx", 0);
if(xxxx<0) {
printf("error with open");
exit(0);
}
int tryread = 1;
int trywrite;
while (tryread > 0) {
char buffer[120];
tryread = read(xxxx, &buffer, 120);
trywrite = write(XYZ, &buffer, 120);
char xyz[3] = "XYZ";
trywrite = write(XYZ, &xyz, 120);
}
}