C 使用函数后未能使用fprintf()
当我运行parsertest时,C 使用函数后未能使用fprintf(),c,file-io,printf,C,File Io,Printf,当我运行parsertest时,stdout中只有一行“helloworld”,add1.txt中没有任何内容。 但是当我删除行时:char*nospace=delespace(行),标准输出显示许多行,这与add.txt的行号相同,“hello world”的行号相同,也与add1.txt中的“hello world”相同 -----------parsettest.c----------------- #include "Parser.c" #define MAXLEN 100 int
stdout
中只有一行“helloworld”,add1.txt中没有任何内容。
但是当我删除行时:char*nospace=delespace(行)代码>,标准输出显示许多行,这与add.txt的行号相同,“hello world”的行号相同,也与add1.txt中的“hello world”相同
-----------parsettest.c-----------------
#include "Parser.c"
#define MAXLEN 100
int main(void){
FILE * fp;
FILE * fp2;
if((fp = fopen("add.txt", "r")) == NULL){
printf("Can't open add.txt");
return 0;
}
if((fp2 = fopen("add1.txt", "w+"))== NULL){
printf("Can't creat add1.txt");
return 0;
}
char * line = (char *)malloc(sizeof(char) * MAXLEN);
while(fgets(line, MAXLEN, fp)){
printf("hello world\n" );
char * nospace = delespace(line);
fprintf(fp2, "hello world\n");
}
fclose(fp);
fclose(fp2);
return 0;
}
-------------Parser.c------------------------
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
char * delespace(char * line){
int i;
for(i = 0; line[i] == ' '; i++)
;
if(line[i] == '\n')
return NULL;
char * newline = malloc(sizeof(line) + 1);
int j = 0;
for(int i = 0; line[i] != '\0'; i++){
if(line[i] == ' ')
continue;
newline[j++] = line[i];
}
newline[j] = '\0';
printf("%s", newline);
return newline;
}
--------------add.txt----------------------------
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/06/add/Add.asm
// Computes R0 = 2 + 3 (R0 refers to RAM[0])
@2
D=A
@3
D=D+A
@0
M=D
--------------parsetset.c-----------------
#包括“Parser.c”
#定义MAXLEN 100
内部主(空){
文件*fp;
文件*fp2;
if((fp=fopen(“add.txt”,“r”))==NULL){
printf(“无法打开add.txt”);
返回0;
}
如果((fp2=fopen(“add1.txt”,“w+”)==NULL){
printf(“无法创建add1.txt”);
返回0;
}
char*line=(char*)malloc(sizeof(char)*MAXLEN);
while(fgets(line,MAXLEN,fp)){
printf(“hello world\n”);
char*nospace=delespace(行);
fprintf(fp2,“你好世界”\n);
}
fclose(fp);
fclose(fp2);
返回0;
}
-------------解析器.c------------------------
#包括
#包括
#包括
#包括
字符*删除空间(字符*行){
int i;
对于(i=0;行[i]='';i++)
;
如果(第[i]行='\n')
返回NULL;
char*newline=malloc(sizeof(line)+1);
int j=0;
对于(int i=0;行[i]!='\0';i++){
如果(第[i]行=“”)
继续;
换行符[j++]=行[i];
}
换行符[j]='\0';
printf(“%s”,换行符);
返回换行符;
}
--------------add.txt----------------------------
//此文件是www.nand2tetris.org的一部分
//还有《计算系统的要素》一书
//作者:尼桑和肖肯,麻省理工学院出版社。
//文件名:projects/06/add/add.asm
//计算R0=2+3(R0表示RAM[0])
@2
D=A
@3
D=D+A
@0
M=D
在char*delespace(char*line)
函数中
char * newline = malloc(sizeof(line) + 1);
上述malloc
将分配指针大小为的内存
因此,当您访问新行
越界时,您将获得未定义的行为
newline[j++]=line[i]代码>
试试下面的方法
char * newline = malloc(strlen(line) + 1);
谢谢你,基兰。但在这样更改之后,似乎输出中的注释发生了变化,它只在标准输出中打印了一行hello world,并在add1.txt中进行了注释。@rubic对我来说,它工作得很好。你错过什么了吗?哦,我知道了,我错过了什么。再次感谢你,基兰。