0

I have a text file myfile.txt, and at the very bottom of it I have.

Thanks for reading, goodnight.\n\n

How would I remove those 2 newline characters? I can open the file for writing, but can't figure out how to remove just those 2 from the very end.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

0

Just truncate the file by 2 characters:

int fd = open("file.txt", O_WRONLY);
fseek(fd, 0L, SEEK_END);
int sz = ftell(fp);
close(fd);
truncate("file.txt", sz - 2);

You are supposed to leave at lease one new line character at the end of a text file, but it isn't a requirement:

Community
  • 1
  • 1
John
  • 3,769
  • 6
  • 30
  • 49
  • 2
    None that I know of. And for sure it doesn't force such a restriction. Just try `printf "word" > text-file` – Diego Jun 20 '15 at 00:35
  • @Diego try doing a hexdump. There is a newline at the end of the file. – John Jun 20 '15 at 01:14
  • 1
    You used `echo` not `printf`. It's different – Diego Jun 20 '15 at 01:16
  • 1
    There is no need to have \n at the end of text file in Linux. Here is simple way to verify that. If you execute in terminal `cat > testfile` type in few characters and execute Ctrl+D and again Ctrl+D testfile will receive content. Now in terminal execute `file testfile` and output is `testfile: ASCII text, with no line terminators` – Filip Bulovic Jun 20 '15 at 02:16
  • 2
    See [No final newline](http://stackoverflow.com/questions/12916352/) for a discussion of some of the problems you can run into if your 'text file' does not end with a newline. You should avoid text files without a final newline. Core Unix doesn't care; some of the text processing tooling does care. – Jonathan Leffler Jun 20 '15 at 03:35
  • See also: [**Why should files end with a newline?**](http://stackoverflow.com/questions/729692/why-should-files-end-with-a-newline) – David C. Rankin Jun 23 '15 at 02:41