C初學者在這裏,我被授予家庭作業分配,我們將使用gedit設計一個程序從命令行讀取文件名並設計一個getNextWord方法。我們只需簡單地打開每個文件並返回單詞,忽略除字母數字字符以外的所有內容(並將大寫字母轉換爲低位)。我掛斷的是,我的老師給了我們strdup()函數來幫助我們以及isspace,alnum等等。無論如何,在查詢本網站上的strdup()以及C基礎知識和網站和其他人一定有我不理解的東西。我的程序編譯(我使用gcc -Wall -pedantic -std = c99 words.c -o words),並且它僅編譯一個警告,即strdup()被隱式使用。在同一個目錄下運行一些文本文件的程序,它會打印出gobbly gook,好像它跑出堆的邊界,然後給出分段錯誤(核心轉儲)。我以爲我也給了它正確的檢查,比如在返回指針的strdup之前在字符數組的末尾加上\ 0等,這是我的代碼;我不期待任何人爲我做我的事,也許觀察會有幫助,因爲我整天研究並找不到問題。感謝您閱讀本(它沒有顯示,但我包括標準輸入輸出,文件stdlib.h,string.h中,文件ctype.hC使用strdup()等從文件中讀取/打印單詞
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_SIZE 256
char* getNextWord(FILE* fd)
{
int index = 0;
int c;
char str[MAX_WORD_SIZE];
while((c = fgetc(fd)) != EOF){
c = fgetc(fd);
if (isspace(c)){
str[index] = '\0';
return (char*) strdup(str);
}
if (((index+1) != (MAX_WORD_SIZE-1)) && (isalnum(c))){
c = tolower(c);
str[index] = c;
index++;
}
else {
index++;
str[index] = '\0';
return (char*) strdup(str);
}
}
return NULL;
}
int main(int argc, char* argv[])
{
char** current = argv;
char* heapedString = NULL;
while (*current)
{
char* filename = *current;
FILE* fd = fopen(filename, "r");
if (fd == NULL)
{
fprintf(stderr,"can't read the file\n");
exit(-1);
}
while ((heapedString = getNextWord(fd)) != NULL)
{
heapedString = getNextWord(fd);
printf("%s\n", heapedString);
free(heapedString);
}
fclose(fd);
current++;
}
return 0;
}