该程序控制台的输出符合预期,但写入文本文件的输出并未反射(reflect)这一点。我相当确定这是因为 y(++) 的增量,但我不确定如何在不扰乱逻辑流程的情况下解决问题,并且到目前为止我的尝试不太成功。我已经为此工作了一段时间,所以如果您以前见过我,请原谅我进展缓慢,我正在边做边学!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define MAX_STR_LEN 120
int main(){
char *cArray[MAX_STR_LEN] = { "example", "dinosaurs" };
char cInput[MAX_STR_LEN] = { 0 };
int y = 0;
FILE *pWrite;
printf("Type your message:\n");
fgets(cInput, MAX_STR_LEN, stdin);
cInput[strlen(cInput) - 1] = 0; /* strip newline from input */
printf("\nInitialised string array:\n");
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
while (cArray[y]){
char * ptr = cInput;
while ((ptr = strstr(ptr, cArray[y])) != NULL){
char *ep = strchr (ptr, ' ');
if (ep) *ep = 0; /* null-terminate at space */
printf("%s\n", ptr);
if (ep) *ep = ' '; /* put the space back */
pWrite = fopen("test.txt", "a");
if ( pWrite != NULL ) {
fprintf(pWrite, "%s\n", ptr++);
fprintf(pWrite, "%s\n", asctime (timeinfo));
fclose(pWrite);
} else {
goto ErrorHandler; //there is a file i/o error
}
}
y++;
}
printf ( "Timestamp: %s", asctime (timeinfo) );
exit(EXIT_SUCCESS); //exit program normally
ErrorHandler:
perror("The following error occurred");
exit(EXIT_FAILURE); //exit program with error
}
控制台输出:
Type your message:
this is an example of dinosaurs
Initialised string array:
example
dinosaurs
Timestamp: Sat Mar 7 16:04:42 2015
Program ended with exit code: 0
文件输出:
example of dinosaurs
Sat Mar 7 16:04:42 2015
dinosaurs
Sat Mar 7 16:04:42 2015
预期文件输出:
Initialised string array:
example
dinosaurs
Timestamp: Sat Mar 7 16:04:42 2015
最佳答案
嗯,对于初学者来说,cArray[y] 永远不会是 NULL.. 它是“示例”、“恐龙”,然后是未定义的。所以外部的 while 循环可能会持续很长一段时间。我认为你想明确定义
char *cArray[] = { "example","dinosaurs",NULL };
这保证了外部 while 循环将终止。但你所问的真正问题实际上并没有你想象的那么糟糕。
首先,在 printf 到控制台之前,您在字符串中显式添加了一个空终止符,但随后在写入文件之前再次将其删除:
将刺痛截断为单个单词:
char *ep = strchr (ptr, ' ');
if (ep) *ep = 0; /* null-terminate at space */
打印
printf("%s\n", ptr);
if (ep) *ep = ' '; /* put the space back */
现在,当我们写入文件时,它又是完整的字符串:
pWrite = fopen("test.txt", "a");
if ( pWrite != NULL ) {
fprintf(pWrite, "%s\n", ptr++);
fprintf(pWrite, "%s\n", asctime (timeinfo));
fclose(pWrite);
因此,当您将字符串写入文件“恐龙的例子”时,您会看到字符串的完整剩余部分。然后第二次,你会看到恐龙,就像你应该看到的那样,因为它恰好是字符串的最后一个单词。
接下来,每次通过内循环打印出日期戳......这就是日期戳显示两次的原因。另外,您根本不会将“初始化字符串数组”字符串写入文件(仅使用 printf,而不是 fprintf)。
希望有帮助。
关于c - 使用 while 循环理解文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911676/