-1

How can i improve the following code so when a file is printed to be printed with the corect extenstion example a text.txt file it should be printed :" test.txt " and not like this" test "

DIR *dir;
struct dirent *ent;
if ((dir = opendir ("/home/gabriel/C workspace/work1/oopproj/Debug/server")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
    if( ! ( (strcmp (ent->d_name ,".") == 0) || (strcmp (ent->d_name ,"..") == 0 ) ) )
        printf ("%s\n", ent->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return 0;
}
  • 1
    This code should do exactly what you want. You probably have some 'test' file without extension in given directory. BTW, the question is tagged as C++, but I'd say this is pure C. – nothrow Feb 03 '14 at 12:39
  • 1
    @Yossarian: It's assuredly not "pure C"; there is abundant POSIX here. – Lightness Races in Orbit Feb 03 '14 at 12:41
  • @LightnessRacesinOrbit, you got the point. However, the tag is misleading anyway – nothrow Feb 03 '14 at 12:41
  • @Yossarian: [There has been discussion on this](http://meta.stackexchange.com/q/158450/155739). The general concensus is that if he's compiling as C++, then he's writing C++, and the original tag should stay in place. But also that we should point out his C++ is non-idiomatic (which you've done). :) – Lightness Races in Orbit Feb 03 '14 at 12:43
  • This code compiles and runs perfectly (minor tweaks: adding include files and putting a main() around it) on my machine (Opensuse Linux 12.3). – Klaas van Gend Feb 03 '14 at 12:44
  • @LightnessRacesinOrbit, ok, but in that case, the correct answer should be 'use boost::filesystem' :-) (thanks for the link, good to know.) – nothrow Feb 03 '14 at 12:44
  • @Yossarian: Feel free to post it ;) – Lightness Races in Orbit Feb 03 '14 at 12:44

1 Answers1

2

It already does.

You have a file called simply test. Rename the file if you want it to have an extension.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055