C语言 如何使用C程序检测任何文件的新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5791117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:29:50  来源:igfitidea点击:

How to detect a new line of any file using C program

carraysfilenewlinescanf

提问by Sanket Lad

I am reading a file of integers. I want to save integers from each line to a new array. For this I want to detect a new line of a file. If anybody knows this please help.

我正在阅读一个整数文件。我想将每一行的整数保存到一个新数组中。为此,我想检测文件的新行。如果有人知道这一点,请帮忙。

The file to be read is as follows

要读取的文件如下

1 2 4 5 6
7 3 2 5 
8 3 
9 7 6 2 

回答by Oliver Charlesworth

Why not use fgets()to get one line at a time from the file? You can then use sscanf()instead of fscanf()to extract the integers.

为什么不使用fgets()一次从文件中获取一行?然后您可以使用sscanf()而不是fscanf()提取整数。

回答by Avinash

#include <stdio.h>
int main ( int argc, char **argv ) {
    FILE *fp = fopen ( "d:\abc.txt", "r");
    char line[1024];
    char ch = getc ( fp );
    int index = 0;
    while ( ch != EOF ) {
        if ( ch != '\n'){
            line[index++] = ch;
        }else {
            line[index] = '
#include<stdio.h>
void main()
{
    FILE *p;
    int n;
    int s=0;
    int a[10];
    p=fopen("C:\numb.txt","r");
    if(p!=NULL)
        printf("file opened");

    while((n=getc(p))!=EOF)
    {   if(n!=NULL && n!='\n')
      {
        printf("\n%d",n);
        a[s]=n;
        ++s;
      }
    }
fclose(p);
getchar();
}
'; index = 0; printf ( "%s\n", line ); } ch = getc ( fp ); } fclose ( fp ); return 0; }

回答by unwind

Use fgets()to read a single line of input at a time. Then use strtol()to parse off an integer, using its "end pointer" feature to figure out where to try again, and loop until you've parsed all the values.

使用fgets()一次读取输入的一行。然后使用它strtol()来解析一个整数,使用它的“结束指针”功能来找出再次尝试的位置,然后循环直到解析完所有值。

回答by radioing

Using getc()for this action is fine but do not forget that getc()returns type is int. Retype to char "works" but you can have a problem with non strict-ASCII input file because EOF = -1 = 0xFFafter retype to char (on most C compilers), i.e. 0xFFcharacters are detected as EOF.

使用getc()这个动作是好的,但不要忘了,getc()收益类型为int。重新键入字符“有效”,但您可能会遇到非严格 ASCII 输入文件的问题,因为EOF = -1 = 0xFF在重新键入字符后(在大多数 C 编译器上),即0xFF字符被检测为EOF.

回答by Priyanka Avhad

##代码##

I'm not sure of the int to char and vice versa conversion but program works for non zero numbers. I tried on visual basic.

我不确定 int 到 char 的转换,反之亦然,但程序适用于非零数字。我试过visual basic。

回答by Reza

If you use reading char by char then recognizing whitespace with '32' and 'enter' by '13' and/or '10'

如果您使用逐个字符读取字符,然后使用 '32' 识别空格,并使用 '13' 和/或 '10' 识别空格