c - 文件读取和字符计数

标签 c file newline argv fgetc

我正在尝试读入文件,然后按字符输出文件。我希望用户输入一个数字,该数字将是要显示的行数。

如果没有以下行,我的代码将显示整个文本文件。 if (y == lineCount) 中断;

当计算的换行符数量等于用户输入的数量时,该行应该中断循环。

我可以计算 newLine 字符的数量并显示它,但是当我尝试在达到一定数量的 newLine 后打破循环时,代码会在 1 个字符后中断

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    FILE *file = fopen( argv[1], "r" );
    int lineCount, x, y;

    printf("enter a number of lines of lines to be displayed\n");
    scanf("&d", &y);


    while  ( ( x = fgetc( file )) != EOF )  //read characters
    {
        printf( "%c", x );       //print character

        if (x == '\n')           //check for newline character
            lineCount++;    

        if (y == lineCount)      //check for newLine character
            break;               //??? y = lineCount after 1 character???
    }

    printf( "%d lines in the text file\n", lineCount );  //testing the newline characters was being read

   fclose( file );
}

最佳答案

您需要 scanf("%d", &y) 而不是 scanf("d", &y)。

关于c - 文件读取和字符计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979474/

相关文章:

c - 无法理解c中的空指针

c - 操作内存时是否需要乘以sizeof(char)?

c - 寻找数组的中位数

c - 对作为参数传递的数组进行打乱的函数

database - 在数据库和 Json 中保存新行

vba - 自动筛选中间有换行符的值(Excel/VBA)

c 套接字文件传输

linux - Linux系统中文件扩展名大小写

file - Sublime Text 2 - 文件不会更新

ruby - Nokogiri to_xml 没有回车