[英]C - Terminal Write and Output to a Text File
我是一名參加 C 入門課程的學生,我們的第一個 C 期中考試即將到來。 我們的測試環境會將我們的操作和 printf 輸出存儲到一個文本文件中。 just in-case.但是,我們的助教建議我們自己使用寫入文件以防萬一。
) to a text file like output.txt?有沒有一種非常簡單的方法可以將我的終端/控制台輸出和輸入(我在之后輸入的內容)復制到像 output.txt 這樣的文本文件中?
我試過
freopen("output.txt","w",stdout);
但這不會將我的 scanf 輸入寫入文本文件。
任何人都可以幫忙嗎?
不要使用 scanf(); 使用 fgets(); 一個例子:
#include <stdio.h>
#include <stdlib.h>
#define Contents_Size 1000
int main()
{
char contents[Contents_Size];
//Opening the file
FILE * fp;
fp = fopen("\myfile.txt", "w"); //"w" = write
//If there is an error
if(fp == NULL)
{
//Exit
printf("Error!\n");
exit(EXIT_FAILURE);
}
//This part require your input
printf("Enter the contents of file: \n");
fgets(contents, Contents_Size, stdin);
//Write your input in file
fputs(contents, fp);
//Close the file
fclose(fp);
return 0;
}
fgest() 將復制您在內容 [] 中的輸入,而 fputs() 會將內容 [] 的每個字符粘貼到您的文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.