我在嘗試從文件中過濾特定單詞並將它們寫入新文件時遇到了一些問題。 我想要做的只是寫下'&'之後的單詞,直到第一個數字。編寫系統調用C,填充垃圾文件
例如(這是我從讀文件的內容):
& some 12 test1 test2
$ thisword 4 no no no no
對於上面的輸入,我只想一些和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>^@^@^@^@^@^@
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@/
我不知道這是什麼垃圾,可有人請幫助?
您的主要聲明語法爲30年以上。 (將參數類型放在函數名稱和正文之間)我們強烈建議您使用現代C編寫。 – abelenky
您的輸入文件('inpfd')被命名爲'outputfile.txt'?並打開ReadOnly?你不覺得這有點呆板嗎? – abelenky
如果您不嘗試檢查系統調用嘗試給您提供的錯誤報告,則您無權理解程序失敗的原因。 –