我一直在嘗試撰寫一個程式,讓用戶以讀取、寫入或附加模式打開 .txt 檔案,然后編輯其內容。
到目前為止,當我運行該程式時,它能夠以任何選定的模式打開檔案,但是最后一個 if 陳述句中的代碼似乎沒有被執行。我已經嘗試了幾件事,但無法使其正常作業。fopen() 函式似乎作業正常,但它之后的代碼位沒有運行。
有人能告訴我為什么它沒有被執行嗎?
我對編碼和 C 還是很陌生,所以我懷疑可能有一些我對語言或計算機系統不了解的東西。我提前道歉,因為我沒有注意到我的代碼和邏輯中有任何明顯的錯誤。我很感激所有的幫助,我們將不勝感激。
這是代碼:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "bsp10048.h"
#include <string.h>
#define MAX_EINGABE 80
/*----- Datei?ffner und Editor -----*/
int main(void)
{
FILE* file_ptr;
char str[200], selection[2], mode[2], name[200];
int repeat = 1;
printf("\nPlease enter filename: ");
fgets(name, 200, stdin);
name[strcspn(name, "\n")] = 0;
strcat(name, ".txt");
printf("\n''r'' = Read-mode (Open file for reading)");
printf("\n''w'' = Write-mode (Create file for writing)");
printf("\n''a'' = Append-mode (Open file for appending)");
/*MODE SELECTION*/
while (repeat) {
printf("\n\nBitte Modus waehlen: ");
fgets(selection, 2, stdin);
switch (selection[0]) {
case 'r':
/*Lesemodus*/
strcpy(mode, "r");
printf("\nRead-mode selected\n");
repeat = 0;
break;
case 'w':
/*Schreibemodus*/
strcpy(mode, "w");
printf("\nWrite-mode selected\n");
repeat = 0;
break;
case 'a':
/*Appelliermodus*/
strcpy(mode, "a");
printf("\nAppend-mode selected\n");
repeat = 0;
break;
default:
printf("\nInvalid mode!");
break;
}
}
if ((file_ptr = fopen(name, mode)) != NULL) {
printf("File successfully opened!");
}
if (mode != "r") {
fgets(str, 200, stdin);
while (str[0] != '\n') {
fprintf(str, 200, file_ptr);
fgets(str, 200, stdin);
}
}
fclose(file_ptr);
exit(0);
}
uj5u.com熱心網友回復:
您的代碼中有多個問題。
- 比較字串:
if (mode == "r")
您不能通過與字串文字進行比較來比較字串。這將比較地址并且很可能永遠不會相同。
該條件將始終為真,因為兩個字串不能具有相同的地址。
您可能會重新訪問您的學習材料并檢查如何正確處理字串。
改用strcmp:
if (strcmp(mode,"r") != 0)
- 撰寫你的輸出:
fprintf(str, 200, file_ptr);
正如 ShadowRanger 在評論中已經提到的那樣,這是錯誤的。您應該收到有關該行的一些警告。fprintf你把引數弄亂了fwrite。
改用這個:
fprintf(file_ptr,"%s\n", str);
- 使用除錯器來觀察你的程式做了什么。
您聲稱該fgets部分中的 theif永遠不會執行。這實際上是不正確的。
您的代碼中有這一行:
fgets(selection, 2, stdin);
這將只讀取 1 個位元組stdin并使用第二個位元組來終止 0 位元組。任何其他字符,包括\n留在緩沖區中。
如果你來這里:
fgets(str, 200, stdin);
while (str[0] != '\n') {
您將只閱讀一次,您的狀況將立即\n成為.strwhilefalse
您應該在上面\n的fgets通話中提供足夠的空間來使用您的。
附帶說明:如果該條件false尚未在第一次迭代中出現,您可能會fprintf因為如前所述傳遞無效引數而面臨分段錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/485436.html
