【发布时间】:2016-08-10 14:28:05
【问题描述】:
这是关于从文本文件中读取。
我有 3 个命令行参数:
- 文本文件名
- 延迟时间
- 要读取多少行。
我想通过用户指定的行号读取该文本文件,直到文本文件结束。
例如,我第一次读取 5 行,然后程序询问 how many line(s) do you want to read?。我会输入 7 它读取第 5 到 12 行。
这将重复直到文件结束。
#include <stdlib.h>
#include <stdio.h>
#include<time.h>
#include <string.h>
void delay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
int countlines(const char *filename) {
FILE *fp = fopen(filename, "r");
int ch, last = '\n';
int lines = 0;
if (fp != NULL) {
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n')
lines++;
last = ch;
}
fclose(fp);
if (last != '\n')
lines++;
}
return lines;
}
int main(int argc, char *arg[])
{
FILE *ptDosya;
char ch;
ch = arg[1][0];
int s2;
int satir = 0;
int spaceCounter=0;
int lineCount, x = 0;
lineCount = atoi(arg[3]);
s2 = atoi(arg[2]);
printf("dosya %d satir icerir.\n", countlines(arg[1]));
ptDosya = fopen(arg[1], "r");
if (ptDosya != NULL)
{
while (ch != EOF&& x < lineCount)
{
ch = getc(ptDosya);
printf("%c", ch);
if (ch == '\n')
{
delay(s2);
x++;
}
}
while (x < countlines(arg[1]))
{
printf("satir sayisi giriniz:");
scanf("%d", &lineCount);
// i don't know what should i do in this loop..
x=x+lineCount;
}
}
else {
printf("dosya bulunamadi");
}
printf("\n\nend of file!\n");
fclose(ptDosya);
return 0;
system("PAUSE");
}
【问题讨论】:
-
你能告诉我们这段代码有什么问题吗? (我看到一个:你的延迟循环是一个 CPU 密集型循环,不是很好!)
-
它需要一些补充。此代码在文本结束前不询问时采用行号。