我對C非常陌生,我試圖按字符讀取一個文件的內容並將它們輸出到流中。但即使使用我的fopen()命令註釋掉了我也會收到segfault(核心轉儲)。我爲什麼要進行分割?
我必須運行一個命令:./a.out < testWords.in> myOut.txt正確執行我的文件。
這是我到目前爲止有:
#include <stdio.h>
void main(char *fileName[])
{
printf("filename is %s.\n",fileName[0]);
//Get file based on a string inputed
FILE *fp=fopen(fileName[0],"r"); //Fetches our file as read only
char ch;
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
//Failed to find/open file. NULL character.
if (fp == 0) printf("Woops! Couldn't open file!\n");
//While not at end of file, grab next char.
else while((ch=fgetc(fp)) != EOF)
{
if (ch == '\n') //on newline
{
//Prints (charCount,wordCount)\n lineCount:
printf("(%d,%d)%c%d:",charCount,wordCount,ch,lineCount);
charCount = 0;
lineCount += 1;
}
else printf("%c",ch); //mirrors char.
}
fclose(fp); //Closes file (gotta be tidy!)
}
因爲您正在調用未定義的行爲。看看你的main()參數。你似乎錯過了一件非常重要的事情。 – WhozCraig