我是c编程的新手。我正在编写一个程序来读取文本文件并将每行存储到char * []数据结构中。我知道如何使用角色,但我不知道如何存储每一行?它需要2D阵列吗?这就是我的代码,但我得到了分段错误。我只是试图打印出我和j来检查它是否有效。 谢谢
#include <stdio.h>
#define NUMBER_LINES 400
int main()
{
char lines[NUMBER_LINES][255];
FILE *fp = fopen("input.txt", "r");
if (fp == 0)
{
return 1;
}
char c;
int i ;
while (fscanf (fp, "%c", &c) == 1)
{
i = 0;
int j;
for (j=0; !(c=='\n'); j++){
lines[i][j] = c;
}
if (c == '\n'){
printf("%s%s\n", lines[i][j]);
i++;
}
}
return 0;
}
答案 0 :(得分:1)
您可以使用矩阵:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_LINES 100
int main(void)
{
int i = 0;
char lines[NUMBER_LINES][255];
FILE *fp = fopen("file.txt", "r");
if (fp == 0)
{
fprintf(stderr, "failed to open input.txt\n");
exit(1);
}
while (i < NUMBER_LINES && fgets(lines[i], sizeof(lines[0]), fp))
{
lines[i][strlen(lines[i])-1] = '\0';
printf("\n%s", lines[i]);
i = i + 1;
}
fclose(fp);
return 0;
}
答案 1 :(得分:0)
代码:
#include "get_next_line.h"
int check_n(char *str)
{
int i;
i = 0;
while (str && str[i])
{
if (str[i] == '\n')
return (i);
i++;
}
return (-1);
}
char *my_strdup_gnl(char *src)
{
int i;
char *str;
int ret;
i = 0;
if ((ret = check_n(src)) == -1)
return (NULL);
if ((str = malloc(sizeof(char) * ret + 1)) == NULL)
return (NULL);
while (i < ret)
{
str[i] = src[i];
i++;
}
str[i] = '\0';
return (str);
}
char *boucle_gnl(char *line, char *buff, int ret, int i)
{
strcat(line, buff);
i = 0;
while (buff[ret + 1] != '\0')
{
buff[i] = buff[ret + 1];
i++;
ret++;
}
buff[ret] = 0;
while (i < READ_SIZE + 1)
{
buff[i] = '\0';
i++;
}
return (line);
}
char *boucle_else_gnl(char *line, char *buff, int ret, int fd)
{
int i;
i = 0;
line = =strcpy(line, buff);
while (i < READ_SIZE + 1)
{
buff[i] = '\0';
i++;
}
if ((ret = read(fd, buff, READ_SIZE)) <= 0)
return (NULL);
return (line);
}
char *get_next_line(const int fd)
{
static char buff[READ_SIZE + 1] = {'\0'};
char *line;
int ret;
int i;
int tmp;
i = 0;
tmp = 0;
line = NULL;
if (!buff[0] && (ret = read(fd, buff, READ_SIZE)) <= 0)
return (NULL);
while (tmp++ != -1)
{
if ((line = my_realloc(line, (tmp * READ_SIZE))) == NULL)
return (NULL);
if ((ret = check_n(buff)) != -1)
return (line = boucle_gnl(line, buff, ret, i), line);
else
{
if ((line = boucle_else_gnl(line, buff, ret, fd)) == NULL)
return (NULL);
}
}
return (NULL);
}
“my_realloc
函数”:
char *my_realloc(char *buff, int nb)
{
char *buf2;
int i;
i = 0;
if ((buf2 = malloc(sizeof(char) * (strlen(buff) + nb + 1))) == NULL)
return (NULL);
if (buff == NULL)
{
buf2[0] = '\0';
return (buf2);
}
while (buff[i])
{
buf2[i] = buff[i];
i++;
}
buf2[i] = '\0';
return (buf2);
}
“get_next_line.h
”:
#ifndef GET_NEXT_LINE_H_
# define GET_NEXT_LINE_H_
#ifndef READ_SIZE
# define READ_SIZE 10000
#include <unistd.h>
#include <stdlib.h>
#endif /* !READ_SIZE */
#endif /* !GET_NEXT_LINE_H_ */