converting text file to CSV file

I am trying to convert a text file to a CSV file.

here is the file I'm trying to convert:
this txt file is meant

to be converted in to

a csv file using the

c on visual studios which

is provided by microsoft corporation

For some reason the output is coming out as:

corporation,corporation,corporation,corporation,corporation,
corporation,corporation,corporation,corporation,corporation,
corporation,corporation,corporation,corporation,corporation,
..........


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>

#define n 5
#define m 5

using namespace std;

	int main() {

	FILE *file;

	file = fopen("file.txt", "r");

	if (file == NULL) {

		printf("no file to open \n");

		return 0;
	}
	else {

		printf("file found \n\n");

		int i = 0, j = 0;

		char values[n][m]; //string of characters //%s

		for (i = 0; i < n; i++) { //assigns values to an array

			for (j = 0; j < m; j++) {

				fscanf(file, "%s", values);
			}
		}
		fclose(file);

		for (i = 0; i < n; i++) { //displays converted data

			for (j = 0; j < m; j++) {

				printf("%s,", values);
			}

			printf("\r\n");
		}

		printf("\n");
		printf("creating .csv file \n\n");

		FILE *f;
		f = fopen("newfile.csv", "w+");

	for (i = 0; i < n; i++) { //puts converted data into the csv file

			for (j = 0; j < m; j++) {

				fprintf(f, "%s,", values);
			}
			fprintf(f, "\r\n");

		}

		fclose(f);

		return 0;
	}
}


There is a problem with assigning a word to the array. I can't seem to figure it out. help is appreciated.

output i want:
this,txt,file,is,meant

to,be,converted,in,to

a,csv,file,using,the

c,on,visual,studios,which

is,provided,by,microsoft,corporation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{
   const char comma = ',';
   string line, word;

   ifstream in( "file.txt" );   if ( !in ) { cerr << "Can't open file"; return 1; }
   ofstream out( "file.csv" );

   while( getline( in, line ) )          // get successive line of text
   {
      stringstream ss( line );
      bool first = true;
      while ( ss >> word )               // get successive words per line
      {
         if ( !first ) out << comma;     // second and later words need a separator
         out << word;
         first = false;
      }
      out << '\n';                      // end of line of output
   }

   in.close();
   out.close();
}

this,txt,file,is,meant
to,be,converted,into
a,csv,file,using,the
c,on,visual,studios,which
is,provided,by,microsoft,corporation
Thanks for the reply lastchance. is there a way to edit the code I already have or is it a lost cause?


Also will the method you posted work with integers as well?
I never learnt C-style input/output, @bkara, so I'm not a position to edit your code. I do think you would find it easier in C++, though.

The code will basically replace whitespace separators in a line (any number of blanks, tabs) by commas. So, if your input consisted of lines like
20  6  2018

it will output
20,6,2018


As long as all you are doing is converting to a CSV file then it will work quite happily. If you are planning to do any numerical work with integers between reading from a .txt file and writing to a .csv file then you will either have to read them as ints or convert the strings to ints.
Last edited on
Alright thanks for your help. It does seem like a smarter method to sense the whitespaces and replace them with a comma. no need to sense whether or not the file has integers or words. Time to learn some C++.
There are a lot of mistakes in your program.

Never include <iostream> in a C program. It's part of C++, not C. The program shouldn't even compile if you are compiling it correctly (i.e., as a C program). "using namespace std" is also C++. Get rid of it.

Don't print "\r\n" for a simple newline. Just use "\n", which will be converted to "\r\n" if the stream is in "text" mode and it's appropriate.

Your problem is mostly caused by this line:
fscanf(file, "%s", values);
If you have maximum warnings enabled you should get a warning about it since values is not a char array but an array of char arrays. The statement will read every string into the exact same place, the first location of the 2D array, so in the end you only have the last word.

n and m are way too small. They only allow 5 words of a maximum of 4 chars each (leaving one char for the terminating '\0').

You are using a double loop to read the strings, but you only need a single loop since each fscanf call reads a word.

To open a file for writing, just use "w", not "w+", which opens it for both writing and reading.

Considering all that, your program is pretty much a lost cause.

Here's a simple C program that might do the job.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main() {
    FILE *fin = fopen("file.txt", "r");
    if (fin == NULL) {
        printf("Error opening input file\n");
        return EXIT_FAILURE;
    }

    FILE *fout = fopen("newfile.csv", "w");
    if (fout == NULL) {
        printf("Error opening output file\n");
        return EXIT_FAILURE;
    }

    char line[1000];
    while (fgets(line, sizeof line, fin) != NULL) {
        bool first_word = true;
        char *word = strtok(line, " \t\n");
        while (word) {
            fprintf(fout, "%s%s", first_word ? "" : ",", word);
            first_word = false;
            word = strtok(NULL, " \t\n");
        }
        fprintf(fout, "\n");
    }

    fclose(fout);
    fclose(fin);

    return 0;
}

Thanks for your help as well tpb, much appreciated.
Last edited on
can anyone please help to implement this question , link to the page is -:

@lastchance , @tpb
please go to this link, i have created a new thread

http://www.cplusplus.com/forum/beginner/238539/
Last edited on
Topic archived. No new replies allowed.