虽然其他人指出了按值传递的问题,但还有另一个可以发生学习的问题。无需预先读取文件以确定字符数或行数,然后倒带文件以读取每一行。
看一眼getline
which 返回读取的字符数。您需要做的就是保留一个sum
变量并在读取所有行后,只需返回(或更新您作为参数提供的指针)即可完成。当然你也可以这样做fscanf
or fgets
通过致电strlen
读完该行后。
以下是一次读取文本文件并确定字符数的简短示例(不带newline
)并将该信息返回给调用函数。正如您需要将指针传递给指针数组一样getInput
,我们将使用作为参数传递的指针来返回line
and character
计入我们的调用函数。如果您声明并调用函数来读取文件,如下所示:
size_t nline = 0; /* placeholders to be filled by readtxtfile */
size_t nchar = 0; /* containing number of lines/chars in file */
...
char **file = readtxtfile (fn, &nline, &nchar);
通过在调用函数中声明变量,然后将指向变量的指针作为参数传递(使用 urnary&
),您可以更新函数中的值,并让这些值可以重新在函数中使用main
(或者你调用的任何函数readtxtfile
from.)
说明这些点的一个简单示例可能是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NMAX 256
char **readtxtfile (char *fn, size_t *idx, size_t *sum);
void prn_chararray (char **ca);
void free_chararray (char **ca);
int main (int argc, char **argv) {
size_t nline = 0; /* placeholders to be filled by readtxtfile */
size_t nchar = 0; /* containing number of lines/chars in file */
char *fn = argc > 1 ? argv[1] : NULL;/* if fn not given, read stdin */
/* read each file into an array of strings,
* number of lines/chars read updated in nline, nchar
*/
char **file = readtxtfile (fn, &nline, &nchar);
/* output number of lines read & chars read and from where */
printf ("\n read '%zu' lines & '%zu' chars from file: %s\n\n",
nline, nchar, fn ? fn : "stdin");
/* simple print function to print all lines */
if (file) prn_chararray (file);
/* simple free memory function */
if (file) free_chararray (file);
return 0;
}
/* simple function using getline to read any text file and return
* the lines read in an array of pointers. user is responsible for
* freeing memory when no longer needed
*/
char **readtxtfile (char *fn, size_t *idx, size_t *sum)
{
char *ln = NULL; /* NULL forces getline to allocate */
size_t n = 0; /* line buf size (0 - use default) */
ssize_t nchr = 0; /* number of chars actually read */
size_t nmax = NMAX; /* check for reallocation */
char **array = NULL; /* array to hold lines read */
FILE *fp = NULL; /* file pointer to open file fn */
/* open / validate file or read stdin */
fp = fn ? fopen (fn, "r") : stdin;
if (!fp) {
fprintf (stderr, "%s() error: file open failed '%s'.", __func__, fn);
return NULL;
}
/* allocate NMAX pointers to char* */
if (!(array = calloc (NMAX, sizeof *array))) {
fprintf (stderr, "%s() error: memory allocation failed.", __func__);
return NULL;
}
/* read each line from stdin - dynamicallly allocated */
while ((nchr = getline (&ln, &n, fp)) != -1)
{
/* strip newline or carriage rtn */
while (nchr > 0 && (ln[nchr-1] == '\n' || ln[nchr-1] == '\r'))
ln[--nchr] = 0;
*sum += nchr; /* add chars in line to sum */
array[*idx] = strdup (ln); /* allocate/copy ln to array */
(*idx)++; /* increment value at index */
if (*idx == nmax) { /* if lines exceed nmax, reallocate */
char **tmp = realloc (array, nmax * 2);
if (!tmp) {
fprintf (stderr, "%s() error: reallocation failed.\n", __func__);
exit (EXIT_FAILURE); /* or return NULL; */
}
array = tmp;
nmax *= 2;
}
}
if (ln) free (ln); /* free memory allocated by getline */
if (fp != stdin) fclose (fp); /* close open file descriptor */
return array;
}
/* print an array of character pointers. */
void prn_chararray (char **ca)
{
register size_t n = 0;
while (ca[n])
{
printf (" arr[%3zu] %s\n", n, ca[n]);
n++;
}
}
/* free array of char* */
void free_chararray (char **ca)
{
if (!ca) return;
register size_t n = 0;
while (ca[n])
free (ca[n++]);
free (ca);
}
使用/输出
$ ./bin/getline_ccount <dat/fc-list-fonts.txt
read '187' lines & '7476' chars from file: stdin
arr[ 0] andalemo.ttf: Andale Mono - Regular
arr[ 1] arialbd.ttf: Arial - Bold
arr[ 2] arialbi.ttf: Arial - Bold Italic
arr[ 3] ariali.ttf: Arial - Italic
arr[ 4] arialnbi.ttf: Arial
arr[ 5] arialnb.ttf: Arial
arr[ 6] arialni.ttf: Arial
arr[ 7] arialn.ttf: Arial
arr[ 8] arial.ttf: Arial - Regular
arr[ 9] ARIALUNI.TTF: Arial Unicode MS - Regular
arr[ 10] ariblk.ttf: Arial
arr[ 11] Bailey Script Regular.ttf: Bailey Script - Regular
arr[ 12] Bailey_Script_Regular.ttf: Bailey Script - Regular
arr[ 13] Belwe Gotisch.ttf: Belwe Gotisch - Regular
arr[ 14] Belwe_Gotisch.ttf: Belwe Gotisch - Regular
<snip>
内存/泄漏检查
每当您在代码中分配/释放内存时,请不要忘记使用内存检查器来确保代码中没有内存错误或泄漏:
$ valgrind ./bin/getline_ccount <dat/fc-list-fonts.txt
==20259== Memcheck, a memory error detector
==20259== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==20259== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==20259== Command: ./bin/getline_readfile_function
==20259==
read '187' line from file: stdin
arr[ 0] andalemo.ttf: Andale Mono - Regular
arr[ 1] arialbd.ttf: Arial - Bold
arr[ 2] arialbi.ttf: Arial - Bold Italic
arr[ 3] ariali.ttf: Arial - Italic
<snip>
==20259==
==20259== HEAP SUMMARY:
==20259== in use at exit: 0 bytes in 0 blocks
==20259== total heap usage: 189 allocs, 189 frees, 9,831 bytes allocated
==20259==
==20259== All heap blocks were freed -- no leaks are possible
==20259==
==20259== For counts of detected and suppressed errors, rerun with: -v
==20259== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
关注评论
您在评论中发布的代码存在几个问题:
for(i = 0; !feof(pFile); ++i) {
fscanf(pFile, "%[^\n]%*c", tempInput);
/* printf("%s\n", tempInput); */
input[i] = (char*)malloc((strlen(tempInput) + 1) * sizeof(char));
strcpy(input[i], tempInput);
printf("%s\n", input[i]);
memset(tempInput, 0, sizeof(tempInput));
}
for(i = 0; i < numInput; ++i) {
convertIntoPost(input[i], output[i]);
}
首先,阅读第一条评论中的链接了解原因feof
使用它来指示循环中的 EOF 时可能会导致问题。二、功能有return values
,利用它们获得优势的能力告诉您是否在工作中使用了正确的功能。
您在尝试硬塞阅读整行内容时遇到的困难fscanf
应该告诉你一些事情......你通过选择格式说明符而陷入的问题"%[^\n]%*c"
读取包含以下内容的行whitespace
是确切的原因fscanf
不是适合这项工作的工具。
为什么?这scanf
创建函数系列来读取discrete价值观。他们的return
是基于:
成功匹配和分配的输入项的数量
使用格式说明符,成功读取的项目数为1
. The *%c
读取并丢弃newline
,但不会添加到项目计数中。当尝试读取可能包含空行的文件时,这会导致一个大问题。然后会发生什么?你经历了一个input failure
and fscanf
回报0
——但这仍然是一条非常有效的路线。当发生这种情况时,不会读取任何内容。您无法检查退货是否为>= 0
因为当你遇到空行时,你就会永远循环......
使用格式说明符,您无法检查EOF
任何一个。为什么?随着scanf
函数族:
价值EOF
如果返回end of input
到达了before要么first successful conversion
or a matching failure
发生。
这在你的情况下永远不会发生,因为你有一个input failure
with fscanf
(not end of input
) 和不matching failure
已经发生了。你开始明白为什么了吗fscanf
可能不是适合这项工作的工具?
C 库提供了两个函数line-oriented
输入。他们是fgets
and getline
。两者都将整行文本读入行缓冲区。这将包括newline
每行末尾(包括空行)。因此,当您使用其中任何一个来阅读文本时,最好删除newline
通过覆盖null-terminating
特点。
使用哪个?和fgets
,您可以通过适当调整字符缓冲区的大小来限制读取的字符数。getline
现在是 C 库的一部分,它提供了返回实际读取的字符数的额外好处(额外的好处),但无论该行有多长,它都会读取该行,因为它会为您动态分配缓冲区。我更喜欢它,但只知道您需要检查它已读取的字符数。
由于我提供了getline
上面的例子,你的读循环可以更好地写成fgets
如下:
while (fgets (tempInput, MAXL, pFile) != NULL) {
nchr = strlen (tempInput);
while (nchr && (tempInput[nchr-1] == '\n' || tempInput[nchr-1] == '\r'))
tempInput[--nchr] = 0; /* strip newlines & carriage returns */
input[i++] = strdup (tempInput); /* allocates & copies tempInput */
}
numInput = i;
接下来,您的分配不需要转换为(char *)
。返回的malloc
and calloc
只是指向分配的内存块(即地址)的指针。 (无论你为什么分配内存,它都是一样的)没有必要sizeof (char)
。总是1
。所以只需写:
input[i] = malloc (strlen(tempInput) + 1);
strcpy (input[i], tempInput);
两者都更方便的方式allocate
and copy
正在使用strdup
. With strdup
,上面两行就变得简单了:
input[i++] = strdup (tempInput); /* allocates & copies */
接下来就不需要了memset
.
memset(tempInput, 0, sizeof(tempInput));
If tempInput
声明为可容纳 100 个字符:tempInput[100]
,您最多可以读取字符串99 char
一遍又一遍地进入同一个缓冲区,而无需将内存归零。为什么?蜇伤是null-terminated
。你不关心之后缓冲区里有什么null-terminator
...
有很多需要考虑的内容。将它们放在一个简短的示例中,您可以执行以下操作:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXL 256
/* dummy function */
void convertIntoPost (char *in, char **out)
{
size_t i = 0, len = strlen (in);
*out = calloc (1, len + 1);
for (i = 0; i < len; i++) {
(*out)[len-i-1] = in[i];
}
}
int main (int argc, char **argv) {
char tempInput[MAXL] = {0};
char **input = NULL, **output = NULL;
size_t i = 0, numInput = 0;
size_t nchr = 0;
FILE *pFile = NULL;
pFile = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!pFile) {
fprintf (stderr, "error: file open failed '%s'.\n",
argv[1] ? argv[1] : "stdin");
return 1;
}
input = calloc (1, MAXL); /* allocate MAXL pointer for input & output */
output = calloc (1, MAXL); /* calloc allocates and sets memory to 0-NULL */
if (!input || !output) { /* validate allocation */
fprintf (stderr, "error: memory allocation failed.\n");
return 1;
}
while (fgets (tempInput, MAXL, pFile) != NULL) {
nchr = strlen (tempInput);
while (nchr && (tempInput[nchr-1] == '\n' || tempInput[nchr-1] == '\r'))
tempInput[--nchr] = 0;
input[i++] = strdup (tempInput); /* allocates & copies */
}
numInput = i;
fclose (pFile);
/* call convertIntoPost with input[i] and &output[i] */
for (i = 0; i < numInput; ++i) {
convertIntoPost (input[i], &output[i]);
printf (" input[%2zu]: %-25s output[%2zu]: %s\n",
i, input[i], i, output[i]);
}
/* free all memory */
for (i = 0; i < numInput; ++i) {
free (input[i]), free (output[i]);
}
free (input), free (output);
return 0;
}
示例输出
$ ./bin/feoffix ../dat/captnjack.txt
input[ 0]: This is a tale output[ 0]: elat a si sihT
input[ 1]: Of Captain Jack Sparrow output[ 1]: worrapS kcaJ niatpaC fO
input[ 2]: A Pirate So Brave output[ 2]: evarB oS etariP A
input[ 3]: On the Seven Seas. output[ 3]: .saeS neveS eht nO
编译代码的注意事项
Always编译你的代码Warnings已启用。这样编译器可以帮助指出代码可能存在歧义的区域等。要在编译时启用警告,只需添加-Wall
and -Wextra
到你的编译字符串。 (如果您确实想要所有警告,请添加-pedantic
(定义:过度关注琐碎细节))。花时间阅读并理解编译器通过警告告诉您什么(它们真的非常好,您将很快了解每个警告的含义)。然后...去解决问题以便你的代码可以编译without任何警告。
只有非常罕见和有限的情况允许“理解并选择允许”保留警告(例如使用无法访问源代码的库时)
因此,将所有内容放在一起,当您编译代码时,至少应该使用以下内容进行编译以进行测试和开发:
gcc -Wall -Wextra -o progname progname.c -g
With gcc
, the -g
选项告诉编译器生成额外的调试信息以供调试器使用gdb
(学习它)。
当您解决了所有错误并准备好最终编译代码时,您将需要添加优化,例如优化级别-On
(这就是资本O
[非零] 其中'n'
是水平1, 2, or 3
(0
为默认值),-Ofast
本质上是-O3
有一些额外的优化)。您可能还想考虑告诉编译器inline
如果可能的话,你的功能-finline-functions
以消除函数调用开销。因此,对于最终编译,您将需要类似的内容:
gcc -Wall -Wextra -finline-functions -Ofast -o progname progname.c
优化可以使性能提高 10 倍,并减少程序执行时间(在某些情况下,性能提高 1000%(通常提高 300-500%))。非常值得添加几个开关。