Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何指示文件的最后一行_C_Arrays - Fatal编程技术网

C 如何指示文件的最后一行

C 如何指示文件的最后一行,c,arrays,C,Arrays,我想逐行读取txt并将其存储到数组中; 我像成功一样,一行一行地存储在阵列中; 我分别使用printf(“%s”,loadtext[I])和I=0,1,2,3-20来检查数组中存储的内容; 但我意识到当我 类型printf(“%d”,i)就在for循环的后面 假设我的txt是这样存储的: I am a jerk I am a noob I am an idiot I am done 我有另一个程序在这个程序运行时向文本文件添加新行。 如何检测我已完成,或者稍后添加的新行是不允许for循环执行

我想逐行读取txt并将其存储到数组中; 我像成功一样,一行一行地存储在阵列中; 我分别使用
printf(“%s”,loadtext[I])
I=0,1,2,3-20
来检查数组中存储的内容; 但我意识到当我 类型
printf(“%d”,i)就在for循环的后面

假设我的txt是这样存储的:

I am a jerk
I am a noob

I am an idiot
I am done
我有另一个程序在这个程序运行时向文本文件添加新行。 如何检测
我已完成
,或者稍后添加的新行是不允许for循环执行如此多次的最后一行

这是我的密码

 #include <stdio.h>
 #include <stdlib.h>
 #include <math.h>
 #include <ctype.h>
 #include <string.h>

int main(){
    FILE *fp = fopen("abc.txt","r");
    int i = 0,j=0,k=0;
    char ch[10000];
    char loadtext[100][100];
    for (i=0; ch[i] != EOF; i++){
        ch[i] = fgetc(fp);
        if (ch[i] != '\n'){
            loadtext[j][k] = ch[i];
            k++;
        }
        if(ch[i] == '\n'){
            loadtext[j][k] = ch[i];
            k=0;
            j++;
        }
    }
    printf("%s", loadtext[0]);
    printf("%s", loadtext[1]);
    printf("%s", loadtext[2]);
    fclose(fp);
    return 0;
}
#包括
#包括
#包括
#包括
#包括
int main(){
文件*fp=fopen(“abc.txt”,“r”);
int i=0,j=0,k=0;
char-ch[10000];
char loadtext[100][100];
对于(i=0;ch[i]!=EOF;i++){
ch[i]=fgetc(fp);
if(ch[i]!='\n'){
loadtext[j][k]=ch[i];
k++;
}
如果(ch[i]='\n'){
loadtext[j][k]=ch[i];
k=0;
j++;
}
}
printf(“%s”,loadtext[0]);
printf(“%s”,loadtext[1]);
printf(“%s”,loadtext[2]);
fclose(fp);
返回0;
}

要将整个文件读入表示行的char指针的“数组”,可以执行以下操作:

#include <stddef.h>  // size_t
#include <stdlib.h>  // EXIT_SUCCESS, EXIT_FAILURE
#include <stdio.h>   // malloc(), realloc(), free(), fgets()
#include <string.h>  // strlen(), strcpy()

enum { BUFFER_SIZE = 30 };  // whatever line length you suspect the input file to be + 1

int main(void)
{
    char const *filename = "test.txt";
    FILE *is = fopen(filename, "r");
    if (!is) {
        fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
        return EXIT_FAILURE;
    }

    int result = EXIT_SUCCESS;  // assume a happy ending
    char buffer[BUFFER_SIZE];
    size_t num_lines = 0;
    char **lines = NULL;

    while (fgets(buffer, sizeof(buffer), is)) {
        ++num_lines;
        char **temp = realloc(lines, num_lines * sizeof(*lines));
        if (!temp) {
            fputs("Not enough memory :(\n\n", stderr);
            fclose(is);
            result = EXIT_FAILURE;
            goto cleanup;
        }
        lines = temp;

        size_t length = strlen(buffer);
        length = strlen(buffer);

        // remove a trailing newline if any:
        if (length && buffer[length - 1] == '\n')
            buffer[--length] = '\0';

        size_t line_length = length;
        lines[num_lines - 1] = malloc((length + 1) * sizeof(*lines));
        if (!lines[num_lines - 1]) {
            fputs("Not enough memory :(\n\n", stderr);
            fclose(is);
            result = EXIT_FAILURE;
            goto cleanup;
        }

        strcpy(lines[num_lines - 1], buffer);

        // as long as the buffer has been filled completely by the previous
        // call to fgets() and a next call to fgets() also succeeds:
        while (length == BUFFER_SIZE - 1 && fgets(buffer, sizeof(buffer), is)) {
            length = strlen(buffer);

            // remove a trailing newline if any:
            if (length && buffer[length - 1] == '\n')
                buffer[--length] = '\0';

            char *temp = realloc(lines[num_lines - 1], line_length + length + 1);
            if (!temp) {
                fputs("Not enough memory :(\n\n", stderr);
                fclose(is);
                result = EXIT_FAILURE;
                goto cleanup;
            }
            lines[num_lines - 1] = temp;
            strcpy(lines[num_lines - 1] + line_length, buffer);
            line_length += length;
        }
    }
    fclose(is);

    // use lines:
    for (size_t i = 0; i < num_lines; ++i)
        puts(lines[i]);

cleanup:
    for (size_t i = 0; i < num_lines; ++i)
        free(lines[i]);
    free(lines);
    return result;
}
#包括//size\t
#包括//退出成功,退出失败
#包括//malloc()、realloc()、free()、fgets()
#包括//strlen(),strcpy()
枚举{BUFFER_SIZE=30};//无论您怀疑输入文件的行长度是+1
内部主(空)
{
char const*filename=“test.txt”;
FILE*is=fopen(文件名,“r”);
如果(!is){
fprintf(stderr,“无法打开\%s\”进行读取:(\n\n”,文件名);
返回退出失败;
}
int result=EXIT_SUCCESS;//假设一个幸福的结局
字符缓冲区[缓冲区大小];
大小\u t数量\u行=0;
字符**行=空;
而(fgets(buffer,sizeof(buffer,is)){
++数量线;
char**temp=realloc(行数、行数*sizeof(*行数));
如果(!temp){
fputs(“内存不足:(\n\n”,stderr);
fclose(is);
结果=退出故障;
去清理;
}
线路=温度;
大小\u t长度=strlen(缓冲区);
长度=strlen(缓冲区);
//删除尾随换行符(如果有):
if(长度和缓冲区[length-1]='\n')
缓冲区[--length]='\0';
尺寸线长度=长度;
行数[num_lines-1]=malloc((长度+1)*sizeof(*行));
如果(!行[num_行-1]){
fputs(“内存不足:(\n\n”,stderr);
fclose(is);
结果=退出故障;
去清理;
}
strcpy(行[num_line-1],缓冲区);
//只要缓冲区已被前一个缓冲区完全填满
//调用fgets()和下一次调用fgets()也会成功:
while(长度==缓冲区大小-1&&fgets(缓冲区,sizeof(缓冲区),is)){
长度=strlen(缓冲区);
//删除尾随换行符(如果有):
if(长度和缓冲区[length-1]='\n')
缓冲区[--length]='\0';
char*temp=realloc(行[num\u line-1],行长度+长度+1);
如果(!temp){
fputs(“内存不足:(\n\n”,stderr);
fclose(is);
结果=退出故障;
去清理;
}
行数[num_line-1]=温度;
strcpy(行[num_line-1]+行长度,缓冲区);
线条长度+=长度;
}
}
fclose(is);
//使用行:
对于(大小i=0;i
仅使用固定大小的二维数组和fgetc()*):
#包括
#包括
#包括
枚举{MAX_LINE=100,MAX_LINE_LENGTH=100};
内部主(空)
{
char const*filename=“test.txt”;
FILE*is=fopen(文件名,“r”);
如果(!is){
fprintf(stderr,“无法打开\%s\”进行读取:(\n\n”,文件名);
返回退出失败;
}
char text[MAX_LINE][MAX_LINE_LENGTH+1]={0};//零初始化数组
//所以我们不必在意
size\u t num\u lines=0;//关于零终止
size\u t current\u column=0;//每行
int-ch;
//只要我们仍然在固定大小数组的边界内
//并且fgetc()不返回EOF
而(num_LINE
代码有各种问题:

  • ch[i]!=EOF
    access
    ch[i]
    分配前!未定义行为(UB)

  • char
    可以是有符号的,也可以是无符号的。
    EOF
    是负数。当
    char
    无符号时,下面是一个无限循环。当
    char
    有符号时,
    ch[i]!=EOF
    可以提前退出循环。相反

    char ch[10000];
    for (i=0; ch[i] != EOF; i++){
      ch[i] = fgetc(fp);
    
  • printf(“%s”,loadtext[0]);
    尝试将
    loadtext[0]
    打印为一个字符串。但是缺少某个空字符,因此不是字符串,这会导致更多的错误

  • 缺少缓冲区索引检查:
    loadtext[j][k]=ch[i];k++<
    
    char ch[10000];
    for (i=0; ch[i] != EOF; i++){
      ch[i] = fgetc(fp);
    
    #define LINES_N 100
    #define LINE_SIZE 100
    
    int main(void) {
      FILE *fp = fopen("abc.txt", "r");
      if (fp) {
        // char ch[10000];
        char loadtext[LINES_N][LINE_SIZE];
        int ch_index = 0;
        int line_count = 0;
        int character;
        int previous_character = '\n';
    
        while ((character = fgetc(fp)) != EOF) {
          // Starting a new line?
          if (previous_character == '\n') {
            if (++line_count > LINES_N) {
              printf("Too many lines\n");
              return EXIT_FAILURE;
            }
          }
          loadtext[line_count - 1][ch_index++] = (char) character;
          loadtext[line_count - 1][ch_index] = '\0';
          if (ch_index + 1 >= LINE_SIZE) {
            printf("Too long a line\n");
            return EXIT_FAILURE;
          }
          previous_character = character;
        }
    
        if (line_count >= 1) printf("%s", loadtext[0]);
        if (line_count >= 2) printf("%s", loadtext[1]);
        if (line_count >= 3) printf("%s", loadtext[2]);
        fclose(fp);
      }
      return 0;
    }