我在尝试从文件中过滤特定单词并将其写入新文件时遇到了一些问题。 我想做的是只写“&”之后的单词,直到第一个数字。
例如(这是我正在读取的文件的内容):
& some 12 test1 test2
$ thisword 4 no no no no
对于上述输入,我只想将单词some 和thisword 写入一个新文件。
我的代码可以正常工作,但是它不仅打印那些单词,还打印垃圾。
int main (argc,argv)
int argc;
char *argv[];
{
int inpfd,outpfd,n;
int i=0;
char tmp[2],buff[BUFFSIZE]; //This is our buffer
//Open the output file of ispell
inpfd = open("outputfile.txt",O_RDONLY);
//Check if open command failed
if(inpfd == -1) {
printf("Failed to open file");
exit(1);
}
//Here we are reading from output file
read(inpfd,buff,999);
buff[999] = '\0';
close(inpfd);
outpfd = open("w.txt",O_WRONLY);
if(outpfd == -1) {
printf("Cannot open file for writing!");
exit(1);
}
//Looping over the Buffer
for (i=0; i <BUFFSIZE; i++) {
printf("This is the char : %c \n",buff[i]);
if(buff[i] == '&') {
i++;
while( !(isdigit(buff[i])) ) { //Write into output file
//As long as we didnt reach
tmp[0] = buff[i]; // To the digit
write(outpfd,tmp,1);
i++;
}
write(outpfd,"\n",1); //Moving to the next line
}
}
close(outpfd);
return 0;
}
这是写入后文件的输出(我只粘贴了一小部分垃圾):
some
thisword
^@^@^@<FD>^?^@^@<80><B2>-<AD><FD>^?^@^@<B0>
<B0>be^@^@^@^@[^X^?^@^@^@<B4>-<AD><FD>^?^@^@s^X<F0>[^X^?^@^@^@<FF>^@^@^@^@^@^@
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@/
我不知道这是什么垃圾,有人可以帮忙吗?
最佳答案
你的问题出在这段代码中
read(inpfd,buff,999);
buff[999] = '\0';
close(inpfd);
你在哪里忽略了你正在阅读的内容的实际长度
你至少应该使用实际读取的数据长度——像这样
int len = read(inpfd,buff,999);
buff[len] = '\0';
close(inpfd);
但是请注意,上面有它自己的问题,因为 read 并不总是一次返回所有内容并且可以提前终止中断等等,但这超出了这个问题的范围。对于非常简单的应用程序,您可能只需进行简单的修改即可。
现在,在 null 终止从读取结果中知道文件的实际长度之后,您还需要修复循环——第一步是让您的外部循环只查看您读取的数据,所以
所以相反
for (i=0; i <BUFFSIZE; i++) {
使用实际长度;
for (i=0; i <len; i++) {
您在循环内的代码也包含几个问题,其中一个是循环终止,您也必须修复这些问题。
关于c - 编写系统调用 C ,用垃圾填充文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41316933/