我在第一年的讲座中得到了一个问题,我无法解决这个问题
问题是试图要求我创建一个程序来读取文本文件中的文本并将其输出到控制台中并计算正在打印的行数并在控制台上看到输出的文本?
这是实际问题的pdf链接。https://drive.google.com/file/d/0B0jqSF8uVDH3MHE3S2FhaHhWMXM/view
这是我在控制台中读取和输出的文本文件的链接。
https://drive.google.com/file/d/0B0jqSF8uVDH3WFBsdExaLXY4RDA/view
这是我制作的代码,有一个错误,我必须删除实际的文本输出才能做到这一点,我不想这样做。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int current = 0;
FILE* p_file = 0;
char name[100];
printf("what filen");
scanf("%s", &name);
p_file = fopen(name, "r");
current = fgetc(p_file);
int count = 0;
while (EOF != current)
{
count = count + 1;
printf("%d: ", count);
printf("%c", current);
current = fgetc(p_file);
}
fclose(p_file);
return 0;
}
请阅读问题,看看您是否可以提供帮助
我正在使用Microsoft Visual Studio 2013?
这可能对你有用。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE* p_file = 0;
char name[100];
char st[100];
printf("what filen");
scanf("%s", name);
p_file = fopen(name, "r");
int count = 0;
while (fgets(st, sizeof st, p_file) != NULL)
{
count = count + 1;
printf("%d: ", count);
printf("%s", st);
}
fclose(p_file);
return 0;
}
你需要计算行数。 因此,您需要检查行尾。 行始终以换行符""和(可选(回车符"\r"结尾。 因此,让我们计算换行符。
逐字节读取会很慢,但适合您的级别。
while (!feof(p_file)) // check for end of file. (EOF != current) that way has not been in use for ages.
{
// get a byte from file
current = fgetc(p_file);
// is it a newline ?
if (current == 'n')
{
++count; // count
printf("nline %d :", count); // only print the line # on a new line.
// the n - our current character, is
// printed as part of the line label.
}
else
{
printf("%c", current);
}
}
差不多就是这样。 打开文件后,您的代码确实需要进行一些错误检查,在对p_File执行任何操作之前,请确保一切正常。 你可能想从第一行插入一行#,也许从1开始,而不是零,我会把它留给你。
像这样:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
FILE *fp;
char filename[FILENAME_MAX+1] = "";
int line_no, line_no_width, ch, pre_ch;
printf("Filename? ");fflush(stdout);
fgets(filename, sizeof filename, stdin);
filename[strcspn(filename, "n")] = 0;//chomp newline
putchar('n');
if((fp = fopen(filename, "r")) == NULL){
perror("fopen:");
exit(EXIT_FAILURE);
}
line_no = 0;
while ((ch = fgetc(fp)) != EOF){
if(ch == 'n'){
++line_no;
}
pre_ch = ch;
}
if(pre_ch != 'n')
++line_no;
for(line_no_width = 0; line_no; line_no /= 10)
++line_no_width;
line_no = 0;
pre_ch = 'n';
rewind(fp);
while ((ch = fgetc(fp)) != EOF){
if(pre_ch == 'n'){
++line_no;
printf("%*d: ", line_no_width, line_no);
}
putchar(ch);
pre_ch = ch;
}
fclose(fp);
if(pre_ch != 'n')
putchar('n');
return 0;
}