所以我有一个作为读取文件打开的输入文件,它是一个疯狂的lib,也是一个将mad-lib复制到输出(写入)文件的函数。输入文件中的一个例句是"我姐姐是一个非常<形容词>人&#34。令牌单词是"<>"中的单词。那么,如果单词是一个标记,我将如何创建一个返回true的布尔函数?我可以使用fscanf吗?
FILE* open_file(char prompt[], char mode[]);
bool istoken(char word[]);
void process_file(FILE* in, FILE* out);
int main(int argc, const char * argv[]) {
FILE* in = NULL;
FILE* out = NULL;
printf("MAD-LIBS Text Processor\n");
printf("The Program will open a mad-libs file, ask you to fill various words, and produce a funny story.\n");
in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");
process_file(in, out);
fclose(in);
fclose(out);
return 0;
}
/* open_file = prompts user for file name & and attempts to open it, if it fails it prompts the user again. */
FILE* open_file(char prompt [], char mode[]) {
char filename[255];
FILE* in;
do {
printf("%s", prompt);
scanf("%s", filename);
in = fopen(filename, mode);
if (in == NULL) {
printf("Unable to open file: %s. Try Again!\n", filename);
}
} while(in == NULL);
return in;
}
/* process_file = processes entire input file and writes it to output file */
void process_file(FILE* in, FILE* out) {
char content[MAX_LEN];
while(fgets(content, MAX_LEN, in) != NULL) {
fprintf(out, "%s", content);
}
}
/* istoken = returns true if word is a token */
bool istoken(char word[]) { //USE FSCANF MAYBE
char target = '<';
return true;
}
答案 0 :(得分:0)
回答你提出的问题:
#include <string.h>
...
bool istoken(char word[])
{
return (word[0]=='<' && word[strlen(word)-1]=='>');
}
当然这完全取决于传入正确的NUL
终止字符串。如果您将指针传递到缓冲区中间的某个位置:
bool istoken(char word[], size_t wordLength)
{
return (word[0]=='<' && word[wordLength-1]=='>')
}
然而,在调用这些函数之前,你需要做一些单词解析工作。