As Pablo Lozano said, you need an auxiliary battery where you have to pass the data from the original so as not to alter the order of the data.
Since you did not specify the language in which you need to do this, I'll give you an example in java.
Basically the program passes the data of the original stack (without altering its order to a .dat file You can modify it to your liking, where before passing the data to the files, you can add / subtract or make any other operation you want.)
public class PasoPilaAlArchivo {
public static void main(String[] args) {
//declaro pila
Stack <String> pilaOriginal = new Stack<String>();
pilaOriginal.push("1");
pilaOriginal.push("2");
pilaOriginal.push("3");
//declaro la pila auxiliar para no alterar el orden de los datos apilados
Stack <String> pilaAux = new Stack<String>();
//paso los datos de pila original al auxiliar
while(!pilaOriginal.isEmpty()){
pilaAux.push(pilaOriginal.pop());
}
// defino la ruta
String ruta = "...definir ruta del archivo";
// declaro el fichero (con la ruta y el nombre)
File fichero = new File(ruta, "numerosPila.dat");
// creo el flujo de salida hacia el fichero, si el fichero es NULL,
// genera una IOexcepcion
try (FileOutputStream flujoSalida = new FileOutputStream(fichero)) {
System.out.println("Escribiendo fichero...");
// el ciclo que llena el buffer con los numeros, si el buffer se
// queda sin memoria,genera la
// excepcion ArrayIndexOutOfBoundsException
// paso el contenido del buffer al archivo a traves del flujo de
// salida
while(!pilaAux.isEmpty()){
byte[] datos = pilaAux.pop().getBytes();
flujoSalida.write(datos);
}
// cierro el flujo de salida
flujoSalida.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e2) {
System.out.println("ERROR: El buffer no tiene mas memoria, modificar su tamaño.");
}
}
}