简体   繁体   English

C-无法将文件存储到字符串数组中(基于断行)

[英]C - Can't store file into an array of strings (based off line break)

I'm pretty new to C and someone "challenged" me to try and create a sorting program using C. I come from languages that are higher-level where doing something like this is easier, but I guess the lower-level intricacies are way over my head. 我对C很陌生,有人“挑战”我尝试使用C创建排序程序。我来自高级语言,这样做比较容易,但是我想低级复杂是这样在我头上。 I haven't implemented the sorting yet, because I've ran across an obstacle (just one of many) along the way. 我还没有实现排序,因为我在执行过程中遇到了一个障碍(只是其中的一个)。

Anyways, here is the code I have so far: 无论如何,这是我到目前为止的代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE *unsortedFile; /* prepare file variable */
    char lineBuffer[100]; /* prepare variable for each line */
    char *listOfLines[100]; /* prepare line array variable to be sorted */
    int n = 0; 
    int i;
    if (argc == 2) /* if a file has been given */
    {
        unsortedFile = fopen(argv[1], "r"); /* open it readonly */
        if (unsortedFile == NULL) /* if it couldn't open */
        {
            printf("Couldn't open the file %s\n", argv[1]);
            printf("Does it exist?\n");
            return -1; /* stop the program here, return non-zero for error */
        }
        printf("original file:\n\n");
        while (fgets(lineBuffer, sizeof(lineBuffer), unsortedFile))
        {
            printf("%s", lineBuffer);
            listOfLines[n] = lineBuffer; /* store line buffer to the array */
            n = ++n; /* increase n for the next array element */
        }
        printf("\nLines to be sorted: %d\n", n);
        for (i = 0; i < n; i++)
        {
            printf("%s", listOfLines[i]);
        }
    } else /* if no or too many args provided */
    {
        printf("\nArgument error - you either didn't supply a filename\n");
        printf("or didn't surround the filename in quotes if it has spaces\n\n");
        return -1; /* return non-zero for error */
    }
}

At this point, you're probably busy vomiting over the messiest spaghetti code you've ever seen... but anyways, the issue occurs with that while statement, I guess. 在这一点上,您可能正忙于呕吐您所见过的最混乱的意大利面条式代码……但是,无论如何,我想这是while语句出现的问题。 The original file prints to the console fine, but I don't think each line is being stored to listOfLines . 原始文件可以很好地打印到控制台,但是我不认为每一行都存储在listOfLines

Here is what's in file.txt , the file I am supplying as an argument to the program: 这是file.txt ,该文件是我作为程序的参数提供的:

zebra
red
abacus
banana

And here is the output of the program: 这是程序的输出:

dustin@DESKTOP-033UL9B:/mnt/c/Users/Dustin/projects/c/sort$ ./sort file.txt
original file:

zebra
red
abacus
banana

Lines to be sorted: 4
banana
banana
banana
banana
dustin@DESKTOP-033UL9B:/mnt/c/Users/Dustin/projects/c/sort$

Looks like the last line of the file is the only one being stored to listOfLines ? 看起来文件的最后一行是存储到listOfLines的唯一listOfLines吗? What could cause this behavior? 是什么导致这种现象?

Thanks in advance! 提前致谢!

listOfLines is an array of pointers. listOfLines是一个指针数组。 All those pointers are set to point to lineBuffer : 所有这些指针都设置为指向lineBuffer

     listOfLines[n] = lineBuffer;

And lineBuffer is repeatedly overwritten by lines from the file. 并且lineBuffer被文件中的行重复覆盖。 The last line is banana , which is the final value of lineBuffer . 最后一行是banana ,这是lineBuffer的最终值。

Your code then prints the values in listOfLines , which are all pointers to lineBuffer . 然后,您的代码将输出listOfLines的值,这些值都是指向lineBuffer指针。


This line is very wrong, by the way (it has undefined behavior): 顺便说一句,这行是非常错误的(它具有未定义的行为):

    n = ++n;

If you want to increment n , that's either 如果要增加n ,要么

n = n + 1;

or 要么

++n;

Basically, don't modify the same variable twice within the same statement. 基本上,不要在同一条语句中两次修改同一变量。

  1. You need an array of char arrays (not array of pointers) 您需要一个char数组数组(而不是指针数组)

Switched: 切换:

char *lineOfLines[100];      // array of pointers
char listOfLines[100][100];  // array of char arrays
  1. Then use strcpy . 然后使用strcpy

Switched: 切换:

listOfLines[n] = lineBuffer;
strcpy(listOfLines[n], lineBuffer);

Working: 工作方式:

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

int main(int argc, char *argv[])
{
    FILE *unsortedFile; /* prepare file variable */
    char lineBuffer[100]; /* prepare variable for each line */
    char listOfLines[100][100]; /* prepare line array variable to be sorted */
    int n = 0; 
    int i;
    if (argc == 2) /* if a file has been given */
    {
        unsortedFile = fopen(argv[1], "r"); /* open it readonly */
        if (unsortedFile == NULL) /* if it couldn't open */
        {
            printf("Couldn't open the file %s\n", argv[1]);
            printf("Does it exist?\n");
            return -1; /* stop the program here, return non-zero for error */
        }
        printf("original file:\n\n");
        while (fgets(lineBuffer, sizeof(lineBuffer), unsortedFile))
        {
            printf("%s", lineBuffer);
            strcpy(listOfLines[n], lineBuffer); /* store line buffer to the array */
            n = n + 1; /* increase n for the next array element */
        }
        printf("\nLines to be sorted: %d\n", n);
        for (i = 0; i < n; i++)
        {
            printf("%s", listOfLines[i]);
        }
    } else /* if no or too many args provided */
    {
        printf("\nArgument error - you either didn't supply a filename\n");
        printf("or didn't surround the filename in quotes if it has spaces\n\n");
        return -1; /* return non-zero for error */
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 逐行读取文件并将行存储在 C 中的字符串数组中 - Read file line by line and store lines in array of strings in C 如何使用 C(每行一个字符串)将字符串数组存储在文件中? - How to store an array of strings in a file using C (one string per line)? C-如何(通过基于用户的输入)将各种字符串存储在结构内部的数组中? - C - How can I store (from user-based input) various strings in an array inside a structure? 从文件读取并将字符串存储到C语言中的多维字符串数组中 - Read From File and Store Strings into a Multidimensional Array of Strings in C 如何从.txt文件中读取已知数量的未知大小的字符串,并将每一行存储在矩阵的一行中(用C表示)? - How can I read a known number of strings of unknown size from a .txt file and store each line in a line of a matrix (in C)? C语言帮助:如何将.txt文件中的字符串存储到字符数组中? 从命令行参数btw读取此.txt文件。 - C language help:How to store strings from a .txt file into a character array? This .txt file is read from a command line argument btw. C将文件逐行读取到字符串数组中并进行排序 - C read file(s) line-by-line into array of Strings and sort 将文件逐行读取到 C 中的字符串数组中 - Reading a file line-by-line into an array of strings in C 无法将字符串复制到C中的字符串数组 - Can't copy string to an array of strings in C 文件到字符串数组(逐行) - File to array of strings (line by line)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM