如何在C中访问getline()中的字符

时间:2016-10-16 01:48:31

标签: c getline

我正在尝试从getline()访问文本,以便扫描它以寻找特殊字符。程序从文件中读取并创建另一个文件但是,我必须从第一个文件中删除注释并将其打印到第二个文件而不注释。在这种情况下,我需要能够读取所有'%'并删除右边的所有内容。这是我作业的一部分,我不是在找人来完成它并作弊。我只需要找到一种方法来将行存储在char数组中,这样我就可以遍历并找到'%'(如果它存在)。

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

int main(int argc, char *argv[]){


    FILE *fp, *fp2;

    char *line = NULL;
    size_t len = 0;
    ssize_t read = 0;
    //int i = 0;

    //line = test;

    fp = fopen("taxDemo.m", "r");
    fp2 = fopen("taxDemoNoComments.m", "w");

    if(fp == NULL)
        exit(EXIT_FAILURE);


    while((read = getline(&line, &len, fp)) != -1){
        /* for (i = 0; i < len; i++){
            test[i] = line;
            line++;
        }
        */

        //printf("%s", test);

        printf("%s", line);

        fprintf(fp2, "%s", line);
    }


    free(line);
    fclose(fp);
    fclose(fp2);

    return 0;
}

2 个答案:

答案 0 :(得分:1)

以下是基于您的代码的解决方案。我添加了一个示例文件的创建和行的分配。

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

int main(int argc, char *argv[]) {

    FILE *fp, *fp2;

    char *line = NULL;
    size_t len = 1024;
    size_t read = 0;

    line = (char*) malloc(len * sizeof(char));
    if (line == NULL) {
        perror("Unable to allocate line...");
        exit(1);
    }
//Create sample file
    fp = fopen("taxDemo.m", "w+");

    for (int i = 0; i < 10; i++) {
        fprintf(fp, "Non commented part of the line %i %% Commented \n", i);
    }
    fclose(fp);
    fp = fopen("taxDemo.m", "r");
    fp2 = fopen("taxDemoNoComments.m", "w");

    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
        for (int i = 0; i < len; i++) {
            if (line[i] == '%')
                line[i] = '\0';
        }

        printf("%s\n", line);

        fprintf(fp2, "%s\n", line);
    }
   free(line);
    fclose(fp);
    fclose(fp2);

    return 0;
}

答案 1 :(得分:0)

  1. 重复查找%行的内容,并在找到时执行您需要执行的操作。

    char* cp = line;
    for ( ; *cp != '\0'; ++cp )
    {
       if ( *cp == '%' )
       {
          // Do what you need to do.
          // If you want to ignore everything after the % but leave the %, use
          *(cp + 1) = '\0';
    
          // If you want to ignore % and everything after it, use
          *cp = '\0';
       }
    }
    
    // Print the line
    
  2. 我建议使用fgets代替getline,因为getline不是标准的C库函数。

    char line[MAX_LINE_LENGTH];   // #define MAX_LINE_LENGTH to suit your needs
    while( fgets(line, sizeof(line), fp) != NULL ){