[英]c reading character one by one from a file?
Say I have a file like so:假设我有一个这样的文件:
1234
56e8
1245
Is there a way I could read one character at a time and perform operations on them?有没有一种方法可以一次读取一个字符并对它们执行操作? Or, is there a way I can read a line and extract each character from it?
或者,有没有一种方法可以读取一行并从中提取每个字符?
I've been trying to use strtok
and use delimiter but can't seem to find a delimiter that can do the job.我一直在尝试使用
strtok
并使用分隔符,但似乎找不到可以完成这项工作的分隔符。
Yes, it is possible.对的,这是可能的。 An easy way to read cha racter by character would be to use
fgetc
:按字符读取字符的一种简单方法是使用
fgetc
:
int c;
FILE *fp = fopen("filename.txt", "r");
if (fp == NULL)
{
printf("Error opening file!\n");
return -1;
}
while ((c = fgetc(fp)) != EOF)
{
// Character is read in `c`
// Do something with it
}
fclose(fp);
As for reading line by line, use fgets
:至于逐行阅读,请使用
fgets
:
char line[100];
FILE *fp = fopen("filename.txt", "r");
if (fp == NULL)
{
printf("Error opening file!\n");
return -1;
}
while (fgets(line, 100, fp) != NULL) /* Reads a line */
{
// One line is stored in `line`
// Do something with it
}
fclose(fp);
No need to use strtok if you want to examine every char.如果要检查每个字符,则无需使用 strtok。
There are many tutorials on this.有很多关于这方面的教程。 This code will read one character at a time.
此代码将一次读取一个字符。
FILE * pFile;
int c;
pFile=fopen ("myfile.txt","r");
if (pFile==NULL)
perror ("Error opening file");
else
{
do {
c = fgetc (pFile);
} while (c != EOF);
}
fclose (pFile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.