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
How to detect a new line of any file using C program
提问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
回答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
回答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' 识别空格

