编写系统调用 C ,用垃圾填充文件

Write system call C , fills file with garbage

我在尝试从文件中过滤特定单词并将其写入新文件时遇到了一些问题。 我想做的是只写“&”之后的单词,直到第一个数字。

例如(这是我正在读取的文件的内容):

& some 12 test1 test2
$ thisword 4 no no no no

对于上述输入,我只想将单词 somethisword 写入新文件。

我的代码可以正常工作,但是它不仅打印那些单词,还打印垃圾。

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] = '[=11=]';
    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>^@^@^@^@^@^@
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@/

我不知道这是什么垃圾,有人可以帮忙吗?

您正在遍历整个缓冲区大小,即 999 个项目。

for (i=0; i <BUFFSIZE;  i++) {

几乎可以肯定输入文件少于 999 项。因此,一旦您处理完提供的输入,您就只是在处理垃圾,直到您的计数器达到 999!

您的问题出在这段代码中

read(inpfd,buff,999);
buff[999] = '[=10=]';
close(inpfd);

您忽略了所阅读内容的实际长度

您至少应该使用实际读取的数据长度 -- 像这样

int len = read(inpfd,buff,999);
buff[len] = '[=11=]';
close(inpfd);

但是请注意,以上内容有其自身的问题,因为 read 并不总是 return 一次完成所有内容,并且可以提前终止中断等,但这超出了这个问题的范围。对于非常简单的应用程序,您可能只需简单修改即可。

现在,在从读取结果中知道文件的实际长度的空终止之后,您还需要修复循环——第一步是让您的外部循环只查看您读取的数据,所以

所以改为

 for (i=0; i <BUFFSIZE;  i++) {

使用实际长度;

 for (i=0; i <len;  i++) {

您在循环内的代码也包含几个问题,其中一个是循环终止,您也必须修复该问题。