K& R练习1-19重新创建一个文件作为参数读取

时间:2015-07-28 19:49:42

标签: c kernighan-and-ritchie

我从一开始就审查K& R练习,并且我将所有想要在stdin中的内容扩展为文件,这意味着将其作为argv传递。关键是在本练习中功能不能正常工作,我认为这是strlen的一些问题,但我无法弄清楚它到底是什么。该函数正确地(显然)反转文件的行,但我总是得到每个反向字符串中第一行的前两个字符。 "写一个反转角色的函数 字符串。用它来编写一个程序,一次一行地反转它的输入"。

#include <stdio.h>
#include <string.h>
const unsigned MAXLINE = 10000;
char* reverse(char string[])
{
    char rev[MAXLINE];
    int i, j;
    for (i = strlen(string)-1, j = 0; i >= 0, j < strlen(string); --i, ++j)
            rev[j] = string[i];
    return rev;
}
unsigned fgetline(char s[], unsigned lim, FILE *file)
{
    unsigned i;
    char c;
    for (i = 0; (c = fgetc(file)) != EOF && c != '\n'; ++i)
            s[i] = c;
    if (c == '\n')
    {
            s[i] = c;
            ++i;
    }
    s[i] = '\0';
    return i;
}
int main(int argc, char *argv[])
{
    FILE *input = fopen(argv[1], "r");
    char line[MAXLINE];
    unsigned len = 0;
    if (argc != 2 || !input)
            puts("INSERT VALID INPUT FILE");
    else
    {
            while ((len = fgetline(line, MAXLINE, input)) > 0)
            {
                    printf("%s\n", reverse(line));
                    putchar('\n');
            }
            fclose(input);
    }
    return 0;
}

2 个答案:

答案 0 :(得分:3)

char字符串'rev'在调用后丢失范围,因此在行为中未定义。考虑将rev in作为参数传递给reverse()。

答案 1 :(得分:1)

我运行了以下代码。

我干净利落地编译

它使用良好的逻辑顺序来设置操作

它在使用之前清除所有缓冲区,哪些 除其他外,确保所有字符串都被终止。

我对它的'&#39;自己的源文件。

我在结果输出中没有看到任何问题

#include <stdio.h>
#include <stdlib.h>  // exit(), EXIT_FAILURE
#include <string.h>

#define MAXLINE  (10000)

void reverse(char src[], char dest[])
{
    size_t i;
    size_t j = 0;

    memset( dest, '\0', MAXLINE);

    for (i = strlen(src)-1; i != 0; --i, ++j)
            dest[j] = src[i];
}


unsigned fgetline(char dest[], FILE *file)
{
    unsigned i;
    int c;
    memset( dest, '\0', MAXLINE);

    for (i = 0; i < (MAXLINE-1) && (c = fgetc(file)) != EOF && c != '\n'; ++i)
            dest[i] = c;

    if (c == '\n')
    {
            dest[i] = c;
            ++i;
    }

    dest[i] = '\0';
    return i;
}


int main(int argc, char *argv[])
{
    if( argc != 2 )
    {
        printf( "USAGE: %s <inputFileName>\n", argv[0]);
        exit( EXIT_FAILURE );
    }

    // implied else, right number of command line parameters

    FILE *input = NULL;
    if( NULL == (input = fopen(argv[1], "r") ) )
    { // then fopen failed
        perror( "fopen for input file failed");
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    char inputLine[MAXLINE] = {'\0'};
    char outputLine[MAXLINE] = {'\0'};

    while (fgetline(inputLine, input))
    {
        reverse(inputLine, outputLine);
        printf("%s\n", outputLine);
        putchar('\n');
    }

    fclose(input);

    return 0;
}