c - c函数从txt文件中逐字符读取,将其转换为int并将其存储在链表中
问题描述
我想从 .txt 文件中逐个字符地读取数字序列,直到找到一个 \n 字符,这就是,直到找到一个输入。然后将这些数字中的每一个转换为整数,并制作一个链表来存储这些整数。位数是未定义的,它可以是 1 或 1 000 000。这是我到目前为止所做的,但我只是不知道如何将它们转换为整数,如何制作实际列表和然后打印它。
void make_seq_list ()
{
struct seq_node *seq_current = seq_head;
int digit_;
printf("sequence:\n");
while ( (digit_ = fgetc("fptr")) != '\n')
{
//???
}
}
这就是我为这个列表定义每个节点的方式:
typedef struct seq_node //declaration of nodes for digit sequence list
{
int digit; //digit already as an int, not char as read from the file
struct seq_node *next;
} seq_node_t;
请注意,在 txt 文件中,序列类似于:
1 2 3 1 //it can go on indefinitely
/*something else*/
提前致谢。
解决方案
digit_ = fgetc("fptr")
这是完全错误的。函数声明fgetc
:
int fgetc(FILE *stream);
所以,如果你想读取文件的上下文,你必须先打开它:
FILE * fptr = fopen("filename", "r"); // filename: input.txt for example.
if(!fptr) {
// handle the error.
}
// now, you can read the digits from the file.
int c = fgetc(fp);
如果您的文件只包含数字(从0
到9
),您可以使用fgetc
逐位读取。伪代码:
FILE * fptr = fopen("input.txt", "r");
if(!fptr) {
// handle the error.
}
while(1) {
int c = fgetc(fp);
if(isdigit(c)) {
int digit = c-'0';
// add "digit" to linked list
} else if (c == '\n') { // quit the loop if you meet the enter character
printf("end of line\n");
break;
} else if(c == ' ') { // this line is optional
printf("space character\n");
}
}
// print the linked list.
对于插入或打印链表,您可以在 google 中搜索。将为您提供大量示例。例如插入和打印链表的例子
推荐阅读
- wpf - 如何定位 WPF 触发器中的兄弟元素?
- javascript - 纯js中的棋盘
- ios - 隐藏滚动视图且高度约束设置为 0 时未删除空格
- c++ - GTEST - 限定名称不在“:”标记之前命名类
- visual-studio-code - Xdebug 在断点处停止但不能一步一步继续
- email - 正则表达式匹配电子邮件签名图像的 cid
- php - php标签系统无法正常工作查询错误
- shell - 使用 EDK2 编译 UEFI 应用程序/驱动程序
- fonts - html canvas绘制字体超出预期空间,为什么以及如何解决?
- python-2.7 - 使用 boto3 Python 从 Amazon S3 下载特定文件夹中的所有文件