Print new line to a text file without carriage return (CR) in windows

允我心安 提交于 2020-01-01 03:29:07

问题


I am writing a program in C that prints a random hexadecimal value to a text file. The printed value has a carriage return (CR) along with a line feed (LF). However, the CR (visible in notepad++) is causing issues when the file is used. Is there a way to print a new line with just the LF and no CR.

This is the code:

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


void main(){
  int hexa_address, numberofAddress;
  char tracefile[50]; //name of file
  int seq_or_rand; //1 for random address; 2 for sequential address

  srand(time(NULL)); //reset the value of the random

  printf("This generator generates 32bits hexadecimal.\n\n");
  printf("Name of file: ");
  scanf("%s", tracefile);
  printf("Random (1) or Sequential (2): ");
  scanf("%d", &seq_or_rand);

  FILE *file;
  file = fopen(tracefile,"w"); // create file

  if(seq_or_rand == 1){ //random generator
    file = fopen(tracefile,"w"); // create file
    for(numberofAddress = 0; numberofAddress<10000;numberofAddress++){ //create 10000 address
        //if(numberofAddress!=0)

        fprintf(file, "0 ");
        int space = 0;

        for(space; space<8; space++){ //remove any 0 from the left
            hexa_address = rand() % 16;
            if(hexa_address != 0){
                fprintf(file,"%x", hexa_address);
                space++;
                break;
            }
            else if(hexa_address == 0 && space == 7){ //in condition of 00000000
                fprintf(file, "0");
                space++;
            }
        }

        for(space; space<8; space++){ //continue generating the remaining address
            hexa_address = rand() % 16;
            fprintf(file,"%x", hexa_address);
        }
        if(numberofAddress!=99999)
            fprintf(file,"\t"); //start a new line, but not on the last one
    }
  }
  else if(seq_or_rand == 2){ //sequential generator
    file = fopen(tracefile,"w"); // create file
    for(numberofAddress = 0; numberofAddress<10000;numberofAddress++){ //create 10000 address
        if(numberofAddress!=0)
            fprintf(file,"\n"); //start a new line, but not on the first one
        fprintf(file,"0 ");
        fprintf(file,"%x", numberofAddress*4);

    }
  }

  else{ //invalid input
      printf("Invalid Input");
      exit(1);
      }

    fclose(file); //done
}

回答1:


Open/create the file in binary mode

file = fopen(tracefile, "wb");
                          ^ Binary mode

Otherwise

fprintf(file,"\n"); /* In text mode this appends two characters. */


来源:https://stackoverflow.com/questions/7579983/print-new-line-to-a-text-file-without-carriage-return-cr-in-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!