[英]Simple C text scanning and printing
我正在編寫一個非常簡單的編輯器。 我有它,以便程序從stdin讀取,然后立即打印到stdout(請參見下面的代碼)。 我想要一個程序來接收文件,然后根據命令打印或在文件中附加更多文本。 閱讀相關問題后,我仍然感到困惑。 我是否同時使用scanf來讀取文件,然后使用printf來打印到同一文件中? 任何澄清都非常感謝。
#include <stdio.h>
#define MAX_LINES 10
char text[MAX_LINES][MAX_LINES];
int main(void){
FILE *infile;
infile = fopen("file.txt", "w");
//check for file
if(infile==NULL){
puts("Error--no file found");
}
int count, x, y;
printf("Enter to quit the program.\n");
for(count=1; count<MAX_LINES+1; count++){
printf("%d: ", count);
fgets(text[count], MAX_LINES, stdin);
}
for(x=0; x<count; x++){
for(y=0;text[x][y];y++){
putchar(text[x][y]);}
putchar('\n');
}
fclose(infile);
return 0;
//end program
}
您的程序不會“從stdin
讀取”,而是從命名文件中讀取,但是不會寫入該文件。
這是另一個困惑
char text[MAX_LINES][MAX_LINES];
這樣會更好
#define MAX_LINES 10
#define MAX_LENGTH 1000
...
char text[MAX_LINES][MAX_LENGTH];
接下來,看看這個循環
for(count=1; count<MAX_LINES+1; count++)
這將忽略數組的第0個元素,並超出最后一個元素的范圍。 它應該是
for(count=0; count<MAX_LINES; count++)
這是用於stdin
,但是如果文件是打開的磁盤文件,請說infile
您應該檢查讀取是否到達文件末尾
fgets(text[count], MAX_LINES, infile);
並替換為
if (fgets(text[count], MAX_LENGTH, infile) == NULL)
break;
您的評論問題有沒有辦法同時讀取infile並將文本添加到infile? 是的,但這是不可行的,因為@JonathanLeffler寫道“首先准備一個新文件” 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.